(* ::Package:: *)

(************************************************************************)
(* This file was generated automatically by the Mathematica front end.  *)
(* It contains Initialization cells from a Notebook file, which         *)
(* typically will have the same name as this file except ending in      *)
(* ".nb" instead of ".m".                                               *)
(*                                                                      *)
(* This file is intended to be loaded into the Mathematica kernel using *)
(* the package loading commands Get or Needs.  Doing so is equivalent   *)
(* to using the Evaluate Initialization Cells menu command in the front *)
(* end.                                                                 *)
(*                                                                      *)
(* DO NOT EDIT THIS FILE.  This entire file is regenerated              *)
(* automatically each time the parent Notebook file is saved in the     *)
(* Mathematica front end.  Any changes you make to this file will be    *)
(* overwritten.                                                         *)
(************************************************************************)



(* Copyright 2006, 2007, 2008, 2009 by Renan Cabrera, David Park, Jean-Francois Gouyet *)


BeginPackage["TensorCalculus5`Tensorial`"];


Tensor::usage="Tensor[A, upindices, downindices] represents a tensor with the label A and the given up and down indices. The list of up and down indices must be equal in length. Missing indices are indicated by Void. Tensor[\[Phi]] represents a scalar tensor.";


Void::usage = "Void is used to indicate a blank slot in the up or down tensor indices.";


SetDerivativeSymbols::usage="SetDerivativeSymbols[{\",\", \";\", \"\[DifferentialD]\", \"\[DifferentialD]\", \"D\", \"d\",\"\[Sterling]\"}] sets the output format derivative symbols to the list of characters. The list is {DifSym, CovSym, TotalDupSym, TotalDdownSym, AbsoluteDupSym, AbsoluteDdownSym, LieDSym}. The default values are as shown. To change one you must reset the entire list."


SetPartialDisplay::usage="SetPartialDisplay[\"CommaMode\"|\"PartialMode\"] will set the display form of unexpanded partial derivatives.\nCommaMode: a comma followed by indices\nPartialMode: a \[PartialD] with subscript indices.";


SetCovariantDisplay::usage="SetCovariantDisplay[\"SemicolonMode\"|\"DelMode\"] will set the display form of unexpanded covariant derivatives.\nSemicolonMode: a semicolon followed by indices\nDelMode: a \[Del] with subscript indices.";


SetLieDisplay::usage="SetLieDisplay[\"PlainMode\"|\"LieMode\"] will set the display form of unexpanded Lie derivatives.\nPlainMode: unformatted\nLieMode: the LDSym with subscript indices.";


TensorLabelFormat::usage="TensorLabelFormat[label, format] will establish the MakeBoxes definitions so that the symbol label will be given the specified display format.\nTensorLabelFormat[{label1, format1}, {label2,  format2},...] will establish formats for multiple labels.";


ClearTensorLabelFormat::usage="ClearTensorLabelFormat[label1, label2, ...] will clear the TensorLabelFormat definitions";


TensorialHelp::usage="TensorialHelp will bring up the Tensorial Help Browser.";


CopyRelease::usage="CopyRelease is a function used with the Tensorial copy/paste palette";


PartialDH::usage="PartialDH is a dummy name used for PartialD when using the Tensorial copy/paste palette.";


CovariantDH::usage="CovariantDH is a dummy name used for CovariantD when using the Tensorial copy/paste palette.";


TotalDH::usage="TotalDH is a dummy name used for TotalD when using the Tensorial copy/paste palette.";


AbsoluteDH::usage="AbsoluteDH is a dummy name used for AbsoluteD when using the Tensorial copy/paste palette.";


LieDH::usage="LieDH is a dummy name used for AbsoluteD when using the Tensorial copy/paste palette.";


ToArrayValues::usage="ToArrayValues[expr] will convert the expression to a vector, matrix or array by expansion and substitution of any stored values.";


ContractArray::usage="ContractArray[tarray, {lev1, lev2}..] will contract the indicated pairs of level numbers in the tensor array tarray.";


DotTensorFactors::usage="DotTensorFactors[order,displayguide:True][term] will convert a product of tensor factors to a Dot product and put them in the order specified. The order is a list of Part specifications for the term. If the optional displayguide argument is True, Tensorial will print a panel display showing the normal slot order that will be used in the expansion of each array.";


ExpandDotArray::usage="ExpandDotArray[tensorpattern, baseindices:Automatic][expr] will expand tensors that fit tensorpattern into arrays and wrap them in MatrixForm. The optional argument transposeorder can be used to transpose the levels of the resulting array. This is intended to be used on equations that have been put in the dot mode with DotTensorFactors.";


DotOperate::usage="DotOperate[position, operation][term] will carry out the operation on the arrays at position and position + 1 in a dot mode tensor expression";


BaseIndices::usage="BaseIndices is the current default list of symbols or integers being used to index components. It is used with unflavored indices and any flavors that have not been declared with DeclareBaseIndices.";


CompleteBaseIndices::usage="CompleteBaseIndices is the complete set of base indices including those associated with flavors.";


DeclareBaseIndices::usage="DeclareBaseIndices[indexlist] sets the number and values of the base indices. Examples: {1,2,3}, {0,1,2,3}, {t,x,y,z}. The number of base indices determines NDim, the dimension of the underlying vector space. The indices are stored in BaseIndices.\nDeclareBaseIndices[standardbaseindices, flavoredindices...] is used to declare multiple sets of base indices associated with different flavors.";


NDim::usage="NDim is the current dimension of the space, obtained from the length of the BaseIndices list. This applies to all indices except those whose flavors have been assigned special base index sets.";


GetBaseIndices::usage="GetBaseIndices[index] will return the list of base indices associated with index. This is the regular BaseIndices unless the flavor of index is one of the special ones declared in DeclareBaseIndices.";


BaseIndexQ::usage="BaseIndexQ[index] returns True if index has a base index value as its raw index and False otherwise. BaseIndexQ takes into account any special flavors used in DeclareBaseIndices.";


CircleTimes::usage="CircleTimes is used to represent full form tensor products. It maintains the order of tensor factors.";


CircleEvalRule::usage="CircleEvalRule resolves expressions like\n(v1\[CircleTimes]v2\[CircleTimes]v3\[CircleTimes]v4)[w1,,w3,] \[Rule] v2\[CircleTimes]v4 v1.w1 v3.w3 \ninto dot products and reduced tensor terms.";


EvaluateSlots::usage="EvaluateSlots[e, g][expr] will evaluate tensor products, involving CircleTimes, on a list of argument slots, which may contain Nulls. The tensor product and slots must be indicial expressions involving basis tensors e. g is the label for the metric tensor. It is assumed that shortcuts have been defined for e and g.";


BasisDotProductRules::usage="BasisDotProductRules[b, g] generates the dot product simplification rules for basis vectors. These convert dot products of basis vectors to the corresponding metric tensor components. b is the label used for basis vectors and g is the label used for the metric tensor.";


ReverseBasisDotProductRules::usage="ReverseBasisDotProductRules[b, g] generates the rules that convert metric tensors into dot products of the basis vectors. b is the label used for basis vectors and g is the label used for the metric tensor.";


(* ::Input:: *)
EvaluateDotProducts::usage="EvaluateDotProducts[e, g][expr] evaluates all Dot products in expr assuming that e are the basis vectors and g is the metric tensor.";


ConstructDirectProduct::usage="ConstructDirectProduct[expr] will convert a direct product of tensor slot expressions to an expression with a single set of slots. Example:\nS[w,x]\[CircleTimes]T[y,z]//ConstructDirectProduct \[Rule] (S\[CircleTimes]T)[w,x,y,z]. S and T may also be CircleTimes expressions involving basis vectors.";


GenerateBasisTensors::usage="GenerateBasisTensors[e, configuration] will generate the set of basis tensors on basis vectors e with a given configuration of up and down basis vectors. The configuration is specified by a String of u's and d's for up and down. It is assumed that tensor shortcuts have been defined for e.";


IndexParsingRules::usage="IndexParsingRules, which is initially an empty List, can be assigned a list of rules that will extract tensors from an expression, usually as a single tensor or tensor product, so they will be parsed by ParseTermIndices. This allows new types of tensor expressions to be added to Tensorial.";


ParseTermIndices::usage="ParseTermIndices[term] will return the lists of indices:\n{dummies, {freeup, freedown}, bad}\n Dummies are indicies that occur up and down exactly once. Free indicies are ones that occur only once. All other indicies that appear in the term are bad.";


RawIndex::usage="RawIndex[index] will extract the raw index from a flavored index. If the raw index is not a Symbol or Integer an error message is issued.";


RawIndex::notindex="`` is not a Symbol, Integer or Flavor.";


ExtractFreeIndices::usage="ExtractFreeIndices[expr] will generate a list, {{upindices...}, {downindices...}}, of free indices for expr. The up and down indices are sorted in standard order. Expr must be an equation with a sum of tensor terms on each side, or a simple sum of tensor terms. If the terms don't all have the same free indices an error message is generated and False is returned.";


FreeIndices::usage="FreeIndices::notmatched is a error message.";


FreeIndices::notmatched="The free indices are not the same in all terms of the expression or some terms have bad indices.";


ExtractDummyIndices::usage="ExtractDummyIndices[expr] will generate a list, {dummies...}, of all the dummy indices present in expr. The dummy indices are sorted in standard order. Expr must be an equation with a sum of tensor terms on each side, or a simple sum of tensor terms. If the terms don't all have the same free indices an error message is generated and False is returned.";


SymbolicIndexQ::usage="SymbolicIndexQ[index] returns true if index is a Symbol or if index is flavor[i_Symbol] where flavor is a currently active flavor.";


RaiseIndex::usage="RaiseIndex[i,j][tensor] will raise the lower index i in tensor and rename it j.\nRaiseIndex[i,j][expr] will raise the index in all Tensors in the expr.";


RaiseIndex::noindex="`` is not a lower index in ``";


LowerIndex::usage="LowerIndex[i,j][tensor] will lower the upper index i in tensor and rename it j.\nLowerIndex[i,j][expr] will lower the index in all Tensors in the expr.";


LowerIndex::noindex="`` is not an upper index in ``";


ReplaceIndex::usage="ReplaceIndex[i,j][tensor] will replace the index i in tensor and rename it j.\nReplaceIndex[i,j][expr] will replace the index in all Tensors in the expr.";


ReplaceIndex::noindex="`` is not an index in ``";


NewIndexChangePatterns::usage="NewIndexChangePatterns is used to specify novel structures that contain indices. They are appended to built-in index patterns. Each pattern is a list of three items {dropped levels, dropped level patterns, structure pattern}. See documentation.";


IndexChange::usage="IndexChange[{{r, i}, {s, j}...}, sign:1, symboliconly:True][expr] will replace the first index in each pair list by the second index in the pair list and multiply the expression by sign, which has the default value of 1. Only symbolic indices will be replaced unless the optional argument symboliconly is set to False./nIndexChange[{r,i}, sign:1][expr] may be used in the case of a single index change. The flavor must be in the indices.";


UpDownSwap::usage="UpDownSwap[dummyindex][term] will swap the up-down positions of the dummy index in the term consisting of simple tensor products.";


SumExpansion::usage="SumExpansion[i,j,.., base:Automatic][expr] will sum on the indices, i, j,..., in the expression. The indices must carry their flavors. The expansions will be done on individual terms on both sides of an equation and within arrays. The range of the sum is over the base list which has the default value of the base indices associated with the index flavor.\nSumExpansion[{i,j,..}, base:Automatic][expr] may also be used.";


ArrayExpansion::usage="ArrayExpansion[i,j,.., base:Automatic][expr] will form an array on the indices, i, j,..., in the expression. The indices must carry their flavors. The first index will be at the highest level in the expansion array. The range of the expansion is over the base list which has the default value of the base indices associated with the index flavor.\nArrayExpansion[{i,j,..}, base:Automatic][expr] may also be used.";


SumArrayExpansion::subset="`` is not a subset of the base indices ``";


EinsteinSum::usage="EinsteinSum[base:Automatic][expr] will do an Einstein summation individually on all terms on both sides of an equation, or all terms in a sum, or on a single term. The range of the sum is over the base list which has the default value of of the base indices associated with the index flavor.";


EinsteinArray::usage="EinsteinArray[base:Automatic][expr] will do an array expansion on the free indices in the expression. The expansion will be done in the sort order of the free indices. The range of the expansion is over the base list which has the default value of of the base indices associated with the index flavor.";


PartialSum::usage="PartialSum[baseindex, newindices][expr] will expand dummy summations of a tensor expression into components that have one or more baseindex and unexpanded remainders. The elements are returned as a sum. Newindices is a list of indices that are used to replace the existing free indices in the expression. Greek indices might be replaced with Latin indices to indicate a restricted further expansion. PartialSum is mapped over arrays, equations and sums.";


PartialSum::newindices="New indices ``, after removing freeindices ``, are insufficient to replace ``";


PartialSum::baseindex="The base index ``, is not in BaseIndices ``";


PartialArray::usage="PartialArray[baseindex, newindices][expr] will expand the free indices of a tensor expression into components that have one or more baseindex indices and an unexpanded remainder. The elements are returned as a List. Newindices is a list of indices that are used to replace the existing free indices in the expression. Greek indices might be replaced with Latin indices to indicate a restricted further expansion. PartialArray is mapped over arrays, equations and sums.";


PartialArray::newindices="New indices ``, after removing dummies ``, are insufficient to replace ``";


PartialArray::baseindex="The base index ``, is not in BaseIndices ``";


EinsteinArgument::usage="EinsteinArgument[x][expr] will expand coordinate tensors with the label x when used as arguments of functions.\nEinsteinArgument[x, f] will expand only on function heads f.";


IndexFlavors::usage="IndexFlavors is a list of the currently declared index flavors. It has the form {{flavorname, flavorform}...} where flavorname is a symbol, such as red or rocket, and flavorform is either an RGBColor or a header such as OverHat.";


DeclareIndexFlavor::usage="DeclareIndexFlavor[{flavorname, flavorform}] will add the index flavor to the IndexFlavors list and establish the Format for displaying indices with the given flavorname. If flavorform is an RGBColor, the index will be displayed in the given color, otherwise an index i will be displayed as flavorform[i], for example OverHat[i].";


ToFlavor::usage="ToFlavor[toflavor, fromflavor:Identity][expr] will convert Tensors in expr to the specified (toflavor) flavor of indices from fromflavor. Fromflavor is an optional argument with the value Automatic. Identity corresponds to indices with no flavor wrapper. Toflavor may be given the value Identity, in which case fromflavor indices are converted to unflavored indices.";


ClearIndexFlavor::usage="ClearIndexFlavor[flavor] will delete flavor from IndexFlavors and clear the associated Format definition.\nClearIndexFlavor[{flavor, form}]:= ClearIndexFlavor[flavor].";


Flavor::notflavor="`` is not a currently declared index flavor.";


IndexFlavorQ::usage="IndexFlavorQ[flavor] returns True if flavor is contained in the IndexFlavors list and False otherwise.";


GetIndexFlavor::usage="GetIndexFlavor[index] will extract the flavor of an index. It returns Identity for indexes without flavors. It returns $Failed if the flavor is not a currently declared flavor.";


TensorSimplify::usage="TensorSimplify[expr] will attempt to simplify a tensor expression by applying declared symmetries and reindexing terms with similar patterns. It is automatically mapped over lists and equations.";


SimplifyTensorSum::usage="SimplifyTensorSum[sum] will check that all terms in a tensor sum have valid indices, that the free indices are the same in all terms, and will simplify the sum by using a minimum number of dummy indices.";


SimplifyTensorSum::badterm="Term `` contains bad indices.";


SimplifyTensorSum::free="Free indices are not the same in all terms.";


PatternReplaceIndex::usage="PatternReplaceIndex[newindexlist, pattern, checkdummies:True][expr] will replace terms in expr using pattern indices in the given pattern, using newindexlist as replacement dummies. If the head of expr is Plus, the routine is mapped onto the individual terms. The number of named index patterns in pattern must be the same as the number of new indices. The substitutions are performed in the sort order of the named index patterns. The pattern should correspond to a single term. The named index patterns should correspond to dummy indices in the entire expression. The routine will check that the pattern indices are dummies in the matched term unless the optional argument, checkdummies, is set to False. In that case it will also replace pattern indices elsewhere in expr.";


PatternReplaceIndex::dummies="Some pattern indices in `` are not dummies.";


PatternReplaceIndex::numindices="The number of pattern indices in `` does not agree with the number of newindices.";


PermuteTensorSlots::usage="PermuteTensorSlots[label, permutation][expr] will permute all tensors with the specified label and order corresponding to the length of permutation, according to the permutation. Permutation must be a permutation of Range[order]. However, not all permutations are correct and this must be used with care.\nPermuteTensorSlots[label] will put all the up slots first and down slots last without reordering within the ups and downs.";


PermuteTensorSlots::permutation="Permutation `` is invalid.";


ExtractTensorSlots::usage="ExtractTensorSlots[Tensor[label, ups, downs] will extract the slots of the tensor and present them as a list {{label, index, \[MinusPlus]1}...} where -1 is used for an up index and +1 is used for a down index.";


SlotsToTensor::usage="SlotsToTensor[slots] will convert the slots obtained with ExtractTensorSlots back to a tensor.";


ExtractTermSlots::usage="ExtractTermSlots[term] will extract the slots of the tensor term in the Mathematica order of the factors and present them as a list {{label, index, \[MinusPlus]1}...} where -1 is used for an up index and +1 is used for a down index.";


CanonicalUpDowns::usage="CanonicalUpDowns[term] will perform UpDownSwaps on dummy indices to put the ups in the lowest Mathematica position.";


UpDownAdjust::usage="UpDownAdjust[sum] will attempt to simplify terms that differ only in the up/down configuration of their dummy indices.";


KroneckerEvaluate::usage="KroneckerEvaluate[\[Delta]][expr] will evaluate Kronecker symbols in expression whose indices are entirely single flavor base indices. This includes generalized Kroneckers";


KroneckerContract::usage="KroneckerContract[\[Delta]][expr] will contract all tensors with label \[Delta], assumed to be generalized Kroneckers, to give a numerical factor times a Kronecker on the free indices.";


KroneckerContract::indices="Kronecker tensor `` does not have equal up and down indices.";


FullKroneckerExpand::usage="FullKroneckerExpand[\[Delta]][expr] will fully expand tensors with label \[Delta], assumed to be generalized Kroneckers, as first order Kroneckers.";


FullKroneckerExpand::indices="Kronecker tensor `` does not have equal up and down indices.";


PartialKroneckerExpand::usage="PartialKroneckerExpand[\[Delta], order, suborder, expandup:True][expr] will expand tensors with label \[Delta], assumed to be generalized Kroneckers, and with order up and down indices, in terms of \[Delta]s with suborder and (order - suborder) indices. The expansion is done on the first suborder up indices, unless the optional 4th argument is set to False, in which case the first suborder down indices are used.";


PartialKroneckerExpand::indices="Kronecker tensor `` does not have equal up and down indices.";


KroneckerAbsorb::usage="KroneckerAbsorb[\[Delta]][expr] will perform all replacement operations of first order mixed tensors with labels \[Delta], assumed to be Kronecker deltas.";


PermutationPseudotensor::usage="PermutationPseudotensor[n] will generate the array of values that correspond to the completely antisymmetric n-dimensional tensor. The Levi-Civita tensor may be constructed from it.";


PermutationSymbolRule::usage="PermutationSymbolRule[e] will substitute values for a permutation pseudotensor symbol with label e. For substitution to occur the indices must be all up or all down, must be base indices and must all be the same flavor. The base indices in their declared order will have a value of 1.";


(* ::Input:: *)
UseCoordinates::usage="UseCoordinates[{x, y, z,...}, coord:x, flavor:Identity][expr] replaces the coordinate \!\(\*SuperscriptBox[\(x\), \(i\)]\) with the i'th symbol in the list everywhere in the expression. coord is the coordinate label and is an optional argument with the default value x. Flavor is an optional argument with the default value of Identity. \nUseCoordinates[coord:x, flavor:Identity][expr] uses the base index symbols established with DeclareBaseIndices.";


CoordinatesToTensors::usage="CoordinatesToTensors[coordinatelist, label:x, flavor:Identity] will convert coordinate Symbols to the corresponding indexed coordinate positions. Label and flavor are optional arguments that designate the tensor label and the index flavor. The order of the symbols in the coordinates list should correspond to the order of the items in the base indices associated with the flavor of the index.";



SymmetrizeSlots::usage="SymmetrizeSlots[][expr] will employ any TensorSymmetries that have been declared.\nSymmetrizeSlots[label, order, symmetry][expr] will apply the symmetry to tensors with the given label and order.";


SymmetrizePattern::usage="SymmetrizePattern[pattern, symmetries][expr] will permute the (anti)symmetrical indices in all terms matching the pattern such that they are ordered according to the pattern and the specified symmetries. The symmetries take the form\n{{-1|0|1, {index1, index2,\[Ellipsis]}}\[Ellipsis]} where -1 is used if the set of indices is antisymmetrical and 1 if they are symmetrical. For each term and symmetry set, the symmetry set is first sorted. The index values are then picked from the values in the corresponding position in the pattern. These are then changed to the sorted values of the set with the appropriate sign.\nindex1, index2,\[Ellipsis] may also be equal length lists of indices. In that case they are each treated as groups of indices that can be interchanged without internal rearrangement. \nSymmetrizePattern[][expr] automatically applies all the pattern symmetries that have been declared with DeclarePatternSymmetries.";


DeclarePatternSymmetries::usage="DeclarePatternSymmetries[pattern, symmetries] declares a pattern symmetry that will be applied by the general command SymmetrizePattern[]. The symmetries are specified as in the SymmetrizePattern command.\nDeclarePatternSymmetries[{pattern, symmetries},..] allows multiple symmetries to be declared at once.";


TensorSymmetry::usage="TensorSymmetry[label, order] holds the tensor symmetry for the given tensor";


PatternSymmetries::usage="PatternSymmetries is a list of pattern symmetries that will all be applied with the SymmetrizePattern[] command.";


Symmetric::usage="Symmetric[ind][expr], calculates the symmetric tensor expression associated with expr for the index list ind.\nSymmetric[list1, list2,...][expr] calculates the symmetric tensor expression for multiple sets of symmetric indices.\nSymmetric is also a head for the definition of symmetric slots in setting tensor symmetries.";


Symmetric::indices="Symmetric indices `` must be all be in the list of up, ``, or all in the list of down, ``, indices.";


AntiSymmetric::usage=" AntiSymmetric[ind][expr], calculates the  antisymmetric tensor expression associated with expr for the index list ind.\nAntiSymmetric[list1, list2,...][expr] calculates the antisymmetric tensor expression for multiple sets of antisymmetric indices.\nAntiSymmetric is also a head for the definition of antisymmetric slots in setting tensor symmetries.";


AntiSymmetric::indices="AntiSymmetric indices `` must be all be in the list of up, ``, or all in the list of down, ``, indices.";


udsymQ::usage="udsymQ[udsym] tests if udsym consists entirely of u and d characters.";


Parseud::usage="Parseud[udsym[args]] will parse a ud expression and return Sequence[uplist,downlist] with Voids in the empty positions.";
Parseud::BadHead="`` is not a symbol consisting solely of 'u's and 'd's.";
Parseud::Arguments="The arguments in `` do not match the number of up and down slots.";



DefineTensor::usage="DefineTensor[label] will define label as a tensor label that can be used with the 'ud\[Ellipsis]' notation of all orders. Label may also be a list of tensor labels. Example: \nDefineTensor[T] allows the usage\nT@uud[a,b,c]";


ClearTensor::usage="DefineTensor[label] will clear the tensor label definition. Label may also be a list of tensor labels.";


DefinedTensors::usage="DefinedTensors is a list of tensor labels that have been given definitions using DefineTensor and have not been subsequently cleared with ClearTensor.";


SetTensorValues::usage="SetTensorValues[Tensor[label, up, down], values, permissive:False] will set the component values of the tensor. The indices can be plain or flavored symbols. Existing values that have differently flavored indices are retained. The order of storage depends upon the sort order of the symbolic indices used in the tensor. The values are stored in UpValues[label]. Setting tensor values deletes any corresponding tensor value rules. If permissive is True, size checking of arrays is skipped.";


SetTensorValues::dim="The number of indices cannot be greater than the number of dimensions of values.";


SetTensorValues::size="The size of each value array must be the same as as the dimension of the corresponding index.";


SetTensorValueRules::usage="SetTensorValueRules[Tensor[label, up, down], values, permissive:False] will establish rules in TensorValueRules[label] for substituting the given values.  The indices can be plain or flavored symbols. Existing rules that have differently flavored indices are retained. The order of storage depends upon the sort order of the raw symbolic indices used in the tensor. Setting tensor values rules deletes any corresponding tensor values. If permissive is True, size checking of arrays is skipped.";


SetTensorValueRules::dim="The number of indices cannot be greater than the number of dimensions of values.";


SetTensorValueRules::size="The size of each value array must be the same as the dimension of the corresponding index.";


TensorValueRules::usage="TensorValueRules[label] holds substitution value rules for Tensors with label.\nTensorValueRules[label1, label2,...] combines the substitution rules for several labels.";


ClearTensorValues::usage="ClearTensorValues[Tensor[label, upindices, downindices]] will clear the component values of the tensor as UpValues for label and also remove any corresponding substitution rules from TensorValueRules[label]. Existing definitions or rules that are different on the lhs are retained.";


SelectedTensorRules::usage="SelectedTensorRules[pattern] will extract all the tensor rules whose left hand sides match the pattern and whose right hand sides are not 0.";


DeclareZeroTensor::usage="DeclareZeroTensor[label] declares that a tensor of any type with the given label will have zero element values when expanded to an array. Times and Plus are also modified so zero tensors combine as zeros.";


MetricSimplify::usage="MetricSimplify[g][expr] will raise, lower or replace indices in product terms involving g and tensors in expr using g as the label for a metric tensor. The metric tensor can have down, up, up/down or down/up indices.\nMetricSimplify[g, True][expr] will enable metric simplification across Partial and Total derivatives.";


CalculateChristoffels::usage="CalculateChristoffels[{x,\[Delta],g,\[CapitalGamma]}, flavor:Identity, simplification:Identity] calculates the up and down Christoffel arrays and returns {upchristoffel, downchristoffel}. Tensor shortcuts and components for the metric g and its inverse must exist. The calculation is done in the indicated flavor. Simplification is a routine that will be used to simplify the components of the arrays.";


CalculateRiemannd::usage="CalculateRiemannd[labels, flavor:Identity, simplifyroutine:Identity] will calculate the down version of the Riemann tensor and return it as an array. labels is the list {x, \[Delta], g, \[CapitalGamma]}. g and \[CapitalGamma] are the symbols for the metric tensor and Christoffel connections. They must have defined shortcuts and have been given tensor values or rules. flavor and simplifyroutine are optional arguments. flavor is the index flavor used in the g and \[CapitalGamma] values. simplifyroutine is applied to each of the independent elements as they are calculated. Only the independent elements are separately calculated and the complete array is generated from them.";


CalculateRRRG::usage="CalculateRRRG[g, riemanndown, flavor:Identity, simplifyroutine:Identity] will calculate Ruddd, Rdd, R, and Gdd, the up version of the Riemann tensor, the Ricci tensor, curvature scalar, and the Einstein tensor. They are returned as arrays in the list {riemann, ricci, curvaturescalar, einstein}. g is the symbol for the metric matrix. riemanndown is the down version of the Riemann tensor in array form. It can be precalculated with CalculateRiemannTensord. Tensor shortcuts must be defined for g and values or rules stored for the up and down metric matrix. flavor is an optional argument that gives the flavor of the g definitions. simplifyroutine is an optional argument that gives a routine to be applied to each of the elements of the arrays.";


CalculateWeyldown::usage="CalculateWeyldown[metric, riemann, ricci, Rscalar, simplifyroutine:Identity] will calculate the all down Weyl conformal tensor given the down metric matrix, the all down riemman array, the all down ricci matrix and the scalar curvature either set or calculated with CalculateRiemannd and CalculateRRRG. A simplication routine may be passed with the last optional argument.";


SetRicciContraction::usage="SetRicciContraction[index:(3|4)] sets the Riemann index on which to contract to obtain the Ricci tensor.";


CovariantCommutator::usage="CovariantCommutator[{c1, c2}, R, d][term] will calculate the covariant commutator, CovariantD[term,{c1,c2}] - CovariantD[term,{c2,c1}], and express the result in terms of the Riemann tensor R. d is the dummy index introduced.";


CovariantCommutator::indices="The term `` has bad indices ``.";


OrthonormalTransformation::usage="OrthonormalTransformation[metric, signature:{(-1,1)..}, simplifyroutine:Identity, samplevalues:None] will calculate the transformation matrix to convert the metric to diagonal Minkowski form given by signature. Simplifyroutine is an optional argument used to simplify elements of the arrays. Samplevalues is an optional argument that gives sample substitutions for the coordinates to aid, if necessary, in the calculation of the signs of the eigenvalues. The transformation matrix from coordinate to orthonormal basis is returned.";


OrthonormalTransformation::signs="Warning, signs of eigenvalues `` do not match signature `` or are undetermined. Permutation matrix omitted for general case.";


LorentzTransformation::usage="LorentzTransformation[\[Beta],n] will return the Lorentz transformation matrix for a boost of velocity \[Beta] in the three dimensional direction given by the n vector.";


PartialD::usage="PartialD[tensor, i]  calculates the partial derivative of the tensor with respect to the coordinate of index i. \n PartialD[tensor, {i,j,...}] represents the covariant derivative with repect to the list of indices.\nOn display a comma precedes the set of partial indices.\n
This is ambiguous until we expand the partial derivative providing the specific coordinate positions using ExpandPartialD. The derivative in this form does can not calculate partial derivatives of components of tensors because the coordinate positions and the Kronecker tensor are not yet specified. Symbols are considered constants when PartialD is used in this form.\n
PartialD[{x,\[Delta],g,\[CapitalGamma]}][tensor, Tensor[x,{i},{Void}]] calculates the partial derivative respect to the ith-coordinate position using coordinate label x and Kronecker tensor label \[Delta].\n
PartialD[{x,\[Delta],g,\[CapitalGamma]}][tensor, {Tensor[x,{i},{Void}]..}] calculates the higher order partial derivative over the coordinate positions. Symbols are not considered constants when the derivative is carried out over coordinates in this form of the partial derivative (with labels)\n
PartialD[{x,\[Delta],g,\[CapitalGamma]}][expr, v] is the partial derivative of expr with respect to the symbol v. When expr is free from tensor objects PartialD is reduced to the standard Mathematica partial derivative function D.";


ExpandPartialD::usage=
"ExpandPartialD[{x,\[Delta],g,\[CapitalGamma]}][ expr ], expands the partial derivative involved in expr using coordinates label x and Kronecker tensor \[Delta].";


NondependentPartialD::usage="NondependentPartialD[{lab1, lab2,...}..][expr] will implement the assumption that Tensor labels, {lab1, lab2,...} are nondependent so that a partial derivative of one with respect to another will be zero. Multiple lists of nondependent tensor labels may be provided";


UsePartialDChainRule::usage="UsePartialDChainRule[coordtensor][expr] will rewrite single partial derivatives in expr using the chain rule with respect to coordtensor.\nUsePartialDChainRule[diffvar1, diffvar2][expr] will rewrite single or multiple partial derivatives with respect to diffvar2 using the chain rule on diffvar1.";


SetScalarSingleCovariantD::usage="SetScalarSingleCovariantD[on:True] will enable or disable the coversion of a single covariant derivative of a scalar tensor to a partial derivative. The optional argument may be True or False and the default is True. Upon initialization of Tensorial the feature is enabled.";


CovariantD::usage="CovariantD[tensor,i] represents the covariant derivative of the tensor with respect to the down index i.\nCovariantD[tensor, {i,j,...}] represents the covariant derivative with repect to the list of down indices indices.\n CovariantD[tensor,ud..[i,j,..] represents the covariant and contravariant derivative with respect to the indices i, j,.... ud... is a series of 'u' and 'd' characters signifying the up and down positions of the covariant indices.\n Symbols are considered constants.";


ExpandCovariantD::usage="ExpandCovariantD[{x,\[Delta],g,\[CapitalGamma]},a][expr] will expand a covariant tensors using x, g and \[CapitalGamma] for the position, metric and Christoffel label, and the dummy index a.\n
ExpandCovariantD[{x,\[Delta],g,\[CapitalGamma]},{a,b,...}][expr] will expand covariant derivatives of higher order using {a,b,...} as dummy indices.\n
Tensorial 5 does not expand contravariant derivatives but the user can use the metric tensor to do it through the expansion of covariant derivatives.
";


ExpandCovariantD::nottensor="A covariant derivative , ``, cannot be expanded because Tensorial cannot assess the tensor nature of the expression.";


BasisExpandCovariantD::usage="BasisExpandCovariantD[{x,\[Delta],g,\[CapitalGamma]},a][expr] will expand a covariant tensors using x, g and \[CapitalGamma] for the position, metric and Christoffel label, and the dummy index a. Base indices are allowed in expr.\n
BasisExpandCovariantD[{x,\[Delta],g,\[CapitalGamma]},{a,b,...}][expr] will expand covariant derivatives of higher order using {a,b,...} as dummy indices. Base indices are allowed in expr.\n
";


TotalD::usage="TotalD[expr, t] calculates the total derivative of expr with respect to the parameter t. Symbols are not considered constants unless they have the Constant attribute.\n 
TotalD[expr, {t,v,...}] represents the covariant derivative with repect to the list of parameters \n 
This derivative can be we expanded in terms of its partial derivative over the coordinate positions using ExpandTotalD.\n
TotalD is reduced to the standard Mathematica Dt if expr is free from tensor objects.";


ExpandTotalD::usage=
"ExpandTotalD[{x, \[Delta], g, \[CapitalGamma]}, a][tensor], expands the total derivative with coordinate positions label x and Kronecker tensor \[Delta] using the dummy index a.\nExpandTotalD[{x, \[Delta], g, \[CapitalGamma]}, {a ,b,...}][tensor], expands the total derivatives of higher order with coordinates label x and Kronecker tensor \[Delta] using the dummy indices a, b, ..."


ExpandTotalD::dummies="Number of dummies `` does not match number of differentiation variables ``";


ReversePartialTotalChainRule::usage="ReversePartialTotalChainRule is a rule that reverses the chain rule expansion of a partial derivative of a total derivative giving a total derivative.";


UseTotalDChainRule::usage="UseTotalDChainRule[coordtensor, labels][expr] will rewrite single total derivatives in expr using the chain rule with respect to coordtensor using labels as the standard set of labels.";


AbsoluteD::usage="AbsoluteD[tensor, t]  represents the absolute derivative of the tensor with respect to the parameter t. \nAbsoluteD[tensor, {t,v,...}] represents the absolute derivative with repect to the list of parameters \nThis derivative is ambiguous until we expand the partial derivative providing the specific coordinate positions using ExpandAbsoluteD."


ExpandAbsoluteD::usage="ExpandAbsoluteD[{x,\[Delta],g,\[CapitalGamma]},{a,b}][expr] will expand a first order absolute derivative of tensors using labels x, g and \[CapitalGamma] for the coordinate positions, metric tensor and Christoffel symbols, and the dummy indices a and b.\nExpandAbsoluteD[{x,\[Delta],g,\[CapitalGamma]},{{a,b}, {c,d},...}][expr] will expand higher order absolute derivatives. \nTwo dummmy indices are needed for each order of expansion."


ExpandAbsoluteD::nottensor="An absolute derivative , ``, cannot be expanded because Tensorial cannot assess the tensor nature of the expression.";


LieD::usage="LieD[tensor, V]  represents the Lie derivative of the tensor with respect to the vector field V.\nLieD[tensor, {U,V...}] represents the Lie derivative with repect to the list of vector fields.\nThis derivative is ambiguous until we expand the partial derivatives, providing the specific coordinate positions using ExpandLieD."


ExpandLieD::usage="ExpandLieD[{x,\[Delta],g,\[CapitalGamma]}, a][expr] will expand a first order Lie derivative of expr using labels x and g for the coordinate positions and metric tensor, and dummy index a.\nExpandLieD[{x,\[Delta],g,\[CapitalGamma]}, {a,b,...}][expr] will expand higher order Lie derivatives using the list {a,b,..} as dummy indices."


UnnestTensor::usage="UnnestTensor removes Tensor wrappers from Tensor expressions.";


TensorTopology::usage="TensorTopology[ T_Times ], gives an ouput of three elements:
   {M_MatrixQ , Tens_List, flavor }, where M is the  generalized adjacency matrix, Tens is the tensor expression stripped of indices and flavor is flavor of the expression, considered homogeneous in the whole tensor term. \n T must be a simple tensor object or the product of tensor obejcts without summation of tensors. This matrix uniquely identifies the topology  of the tensor expression and is invariant under a change of dummy variables, but assumes homogeneous flavor of indices.
\n The option \"Symmetries\"->True indicates to consider the predefined symmetries. This option is by default False, and TensorTopology does not consider symmetries.  
\n The practical use of this function is limited by the cost of the evaluation that grows as the factorial of the number of tensor factors.";


TensorTopologySameQ::usage="TensorTopologyMatchQ[A,B] Boolean function that established the topological equivalence of Tensors A and B. ";


TensorCanonicalForm::usage="TensorCanonicalForm[dummyList_List][T_Times], writes the tensor term T in a canonical form using the List dummyList as sum indices. \n It can only be applied to Tensor or CovariantD objects.
\n The list of dummy indices can be larger than the needed minimum. 
\n The practical use of this function is limited by the cost of the evaluation that grows as the factorial of the number of tensor factors.
\n The option \"Symmetries\"->True indicates to consider the predefined symmetries. In this case the free indices are sorted whenever the indicated symmetries allow them to move.
 The default option is \"Symmetries\"->False, and TensorCanonicalForm does not consider symmetries.  ";


TensorGraphRules::usage="TensorGraphRules[Tensor_Times,options], 
 gives a list of rules representing the cross of the indices among the tensors and the free indices of each tensor. This list is intended to be directly used as input for the Mathematica function GraphPlot. The nodes of the graph are the different tensors and the free indices.
 \n There are two options with the following default values \"LabelForm\"-> \"FullLabel\"   and \"FreeIndices\"->True.
 \n  \"FreeIndices\"->True indicates to consider the free indices, otherwise \"FreeIndices\"->False indicates to ignore the free indices.
 \n Alternatively \"LabelForm\"-> \"SimpleLabel\" can be used to label the nodes only with the tensor label and \"LabelForm\"-> \"FullTensor\" to use the complete tensor as label.
  \n It does not have resolution to distinguish the order of the indices inside a given primitive Tensor object. This means that it ignores possible symmetries that can distinguish different tensors. 
 \n It does not distinguish  covariant or contravariant or partial derivative indices.
\n The partial derivatives must be in unexpanded simple index form.
 \n Two tensors with the same graph are not necesarily linearly dependent but two tensors with different graphs are definitely linearly independent.
\n The practical use of this function is limited by the cost of the evaluation that grows as the factorial of the number of tensor factors."


TensorGather::usage="TensorGather[T_List], splits the list of tensors T in classes such that two classes will have different number of tensor factors or different number covariant derivatives or different number of partial derivatives or different GrapPlot's generated by TensorGraphRules.";


TensorTopologyGather::usage="TensorTopologyGather[T_List], splits the list of tensors T in classes with the same tensor topology";


TensorClusterFactors::usage="TensorClusterFactors[T] finds the factor clusters that do not cross indices with the rest of the factors and returns a list of the clusters."


TensorClusterFactors::badargument="Bad input argument";


TensorTopology::badargument="Bad input argument";


TensorCanonicalForm::badargument="Bad input argument";


(* ::Input:: *)
FreeTensorQ::usage="FreeTensorQ[ expr ], gives True or False if expr contains a Tensor "


(* ::Input:: *)
FreeTotalDQ::usage="FreeTotalDQ[ expr ], gives True or False if expr contains a total derivative "


Begin["`Private`"]


LinearBreakout[f__][vars__][expr_]:=expr//.{(g:Alternatives@@{f})[p1___,a_+b__,p2___]:>g[p1,a,p2]+g[p1,Plus[b],p2],(g:Alternatives@@{f})[p1___,a_ b:Alternatives@@{vars},p2___]:>a g[p1,b,p2]}


PushOnto[argslist_List,ontolist_List][expr_]:=
Module[{onto=Alternatives@@ontolist},
expr/.(h_/;\[Not]FreeQ[h,onto])@@argslist:>(h/.a_/;MatchQ[a,onto]->a@@argslist)
]


PushOnto[ontolist_List][(head_)[arglist___]]:=
Module[{onto=Alternatives@@ontolist},
head/.a_/;MatchQ[a,onto]:>a[arglist]
]


MapLevelParts[func_,part:{toppart___Integer?Positive,subp:{_Integer?Positive,eprest__Integer?Positive}}][expr_]:=
Module[{work,subparts,npos,null,i,nnull=Length[{eprest}],tempfunc},
work=tempfunc@Part[expr,Sequence@@part];
subparts=Thread[{toppart,subp}];
newparts={work,Table[null[i],{i,1,nnull}]}//Flatten;
npos=Partition[Range[nnull+1],1];
work=ReplacePart[expr,newparts,subparts,npos]/.null[_]->Sequence[];
work/.tempfunc->func
]


MapLevelPatterns[func_,{toppart___Integer?Positive,{pattern_}}][expr_]:=
Module[{work,levelpos},
work=Part[expr,toppart];
levelpos=Flatten@Position[work,pattern,{1},Heads->False];
Switch[Length[levelpos],
0,expr,
1,MapAt[func,expr,Flatten[{toppart,levelpos}]],
_,expr//MapLevelParts[func,{toppart,levelpos}]]
]


SetDerivativeSymbols[list:{_String,_String,_String,_String,_String,_String,_String}]:=
{DifSym,CovSym,TDu,TDd,ADu,ADd,LDSym}=list;


SetLieDisplay[mode:"PlainMode"|"LieMode"]:=
Switch[mode,
"PlainMode",MakeBoxes[LieD[T_,V__],form:StandardForm|TraditionalForm]=.,
"LieMode",MakeBoxes[LieD[T_,V__],form:StandardForm|TraditionalForm]:=
Switch[T,
Tensor[_,_,_]|Tensor[Tensor[_Symbol]]|Tensor[_Symbol],
InterpretationBox[#1,#2,Editable->False]&@@{TagBox[RowBox[{SubscriptBox[LDSym,RowBox[MakeBoxes[#,form]&/@Flatten[{V}]]],"\[VeryThinSpace]",MakeBoxes[T,form]}],LieD,SyntaxForm->"Wedge"],LieD[T,V]},
_,
InterpretationBox[#1,#2,Editable->False]&@@{TagBox[RowBox[{SubscriptBox[LDSym,RowBox[MakeBoxes[#,form]&/@Flatten[{V}]]],"\[NegativeVeryThinSpace]",RowBox[{"(",MakeBoxes[T,form],")"}]}],LieD,SyntaxForm->"Wedge"],LieD[T,V]}]]


SetPartialDisplay[mode:"CommaMode"|"PartialMode"]:=
Switch[mode,
"CommaMode",MakeBoxes[PartialD[t_,indices_],form:StandardForm|TraditionalForm]:=
Module[{windx=Flatten[{indices}]},
If[MatchQ[t, Tensor[_,_,_]|Tensor[f_Symbol]],
InterpretationBox[#1,#2,Editable->False]&@@{SubscriptBox[MakeBoxes[t,form],RowBox[{DifSym,RowBox@(MakeBoxes[#,form]&/@windx)}]],PartialD[t,indices]},
InterpretationBox[#1,#2,Editable->False]&@@{SubscriptBox[RowBox[{"(",MakeBoxes[t,form],")"}],RowBox[{DifSym,RowBox@(MakeBoxes[#,form]&/@windx)}]],PartialD[t,indices]}]],
"PartialMode",MakeBoxes[PartialD[t_,indices_],form:StandardForm|TraditionalForm]:=
Module[{windx=Flatten[{indices}]},
Switch[t,
Tensor[_,_,_]|Tensor[Tensor[_Symbol]]|Tensor[_Symbol|_Tensor]|PartialD[__],
InterpretationBox[#1,#2,Editable->False]&@@{RowBox[{SubscriptBox["\[PartialD]",RowBox@(MakeBoxes[#,form]&/@windx)],MakeBoxes[t,form]}],PartialD[t,indices]},
_,
InterpretationBox[#1,#2,Editable->False]&@@{RowBox[{SubscriptBox["\[PartialD]",RowBox@(MakeBoxes[#,form]&/@windx)],RowBox[{"(",MakeBoxes[t,form],")"}]}],PartialD[t,indices]}]]]


SetCovariantDisplay[mode : "SemicolonMode" | "DelMode"] :=
 Switch[mode,
  "SemicolonMode", MakeBoxes[CovariantD[t_, upindices__,downindices__], form : StandardForm | TraditionalForm] :=
   Module[{downindx = Flatten[{downindices}]/.Void-> Style[" ",ShowContents->False],upindx = Flatten[{upindices}]/.Void-> Style[" ",ShowContents->False]},
    If[MatchQ[t, Tensor[_, _, _] | Tensor[_Symbol]],
     InterpretationBox[#1, #2, Editable -> False] & @@ {SubsuperscriptBox[MakeBoxes[t, form], RowBox[{CovSym, RowBox@(MakeBoxes[#, form] & /@ downindx)}] ,RowBox[{ToBoxes[Invisible[CovSym],form], RowBox@(MakeBoxes[#, form] & /@ upindx)}]], CovariantD[t, upindices,downindices]},
     InterpretationBox[#1, #2, Editable -> False] & @@ {SubsuperscriptBox[RowBox[{"(", MakeBoxes[t, form], ")"}], RowBox[{CovSym, RowBox@(MakeBoxes[#, form] & /@ downindx)}],RowBox[{ToBoxes[Invisible[CovSym],form], RowBox@(MakeBoxes[#, form] & /@ upindx)}]], CovariantD[t, upindices,downindices]}]],
  "DelMode", MakeBoxes[CovariantD[t_, upindices_,downindices_], form : StandardForm | TraditionalForm] :=
   Module[{downindx = Flatten[{downindices}]/.Void-> Style[" ",ShowContents->False],upindx = Flatten[{upindices}]/.Void-> Style[" ",ShowContents->False]},
    Switch[t,
     Tensor[_, _, _] | Tensor[Tensor[_Symbol]] | Tensor[_Symbol | _Tensor] | CovariantD[__],
     InterpretationBox[#1, #2, Editable -> False] & @@ {RowBox[{SubsuperscriptBox["\[Del]", RowBox@(MakeBoxes[#, form] & /@ downindx), RowBox@(MakeBoxes[#, form] & /@ upindx) ], MakeBoxes[t, form]}], CovariantD[t, upindices,downindices]},
     _,
     InterpretationBox[#1, #2, Editable -> False] & @@ {RowBox[{SubsuperscriptBox["\[Del]", RowBox@(MakeBoxes[#, form] & /@ downindx), RowBox@(MakeBoxes[#, form] & /@ upindx)], RowBox[{"(", MakeBoxes[t, form], ")"}]}], CovariantD[t,upindices,downindices]}]]]



MakeBoxes[Tensor[A_],form:StandardForm|TraditionalForm]:=InterpretationBox[#1,#2,Editable->False]&@@{MakeBoxes[A,form],Tensor[A]}


MakeBoxes[Tensor[A_,up_List,down_List],form:StandardForm|TraditionalForm]:=Module[{newdown=down,newup=up,makespace},makespace=If[#1===Void,Style[#2,ShowContents->False],#1]&;newup=Inner[makespace,newup,newdown,List];newdown=Inner[makespace,newdown,newup,List];(InterpretationBox[#1,#2,Editable->False,BaseStyle->{AutoMultiplicationSymbol->False}
]&)@@{SubsuperscriptBox[MakeBoxes[A,form],
RowBox[(MakeBoxes[#1,form]&)/@newdown],RowBox[(MakeBoxes[#1,form]&)/@newup]],Tensor[A,up,down]}]


Unprotect[Power];
Format[Power[a_/;\[Not]FreeQ[{Head[a]},Tensor|PartialD|TotalD|AbsoluteD|HoldForm|Dt],power_],TraditionalForm]:=DisplayForm[SuperscriptBox[RowBox[{"(",ToBoxes[a,TraditionalForm],")"}],power]];
Format[Power[a_/;\[Not]FreeQ[{Head[a]},Tensor|PartialD|TotalD|AbsoluteD|HoldForm|Dt],power_]]:=DisplayForm[SuperscriptBox[RowBox[{"(",ToBoxes[a],")"}],power]];
Protect[Power];


MakeBoxes[PartialD[labs:{_,_,_,_}][w_,Tx_Tensor|Tx_Symbol],form:StandardForm|TraditionalForm]:=InterpretationBox[#1,#2,Editable->False]&@@{FractionBox[RowBox[{"\[PartialD]",MakeBoxes[w,form]}],RowBox[{"\[PartialD]",MakeBoxes[Tx,form]}]],PartialD[labs][w,Tx]}


MakeBoxes[PartialD[labs:{_,_,_,_}][w_,Tx_List],form:StandardForm|TraditionalForm]:=Module[{p=Length[Tx],denomboxes},
denomboxes=RowBox@Flatten@MapThread[{"\[PartialD]",MakeBoxes[#]}&,{Tx}];
InterpretationBox[#1,#2,Editable->False]&@@{FractionBox[RowBox[{SuperscriptBox["\[PartialD]",ToString[p]],MakeBoxes[w,form]}],denomboxes],PartialD[labs][w,Tx]}]


MakeBoxes[TotalD[t_],form:StandardForm|TraditionalForm]:=InterpretationBox[#1,#2,Editable->False]&@@{RowBox[{TDu,MakeBoxes[t,form]}],TotalD[t]}


MakeBoxes[TotalD[expr_,t_/;\[Not]VectorQ[t]],form:StandardForm|TraditionalForm]:=
InterpretationBox[#1,#2]&@@{FractionBox[RowBox[{TDu,MakeBoxes[expr,form]}],RowBox[{TDd,MakeBoxes[t,form]}]],TotalD[expr,t]}


MakeBoxes[TotalD[expr_,t:{__}],form:StandardForm|TraditionalForm]:=
Module[{p=Length[t],numboxes,denomboxes},
numboxes=
If[p==1,
RowBox[{TDu,MakeBoxes[expr,form]}],
RowBox[{SuperscriptBox[TDu,ToString[p]],MakeBoxes[expr,form]}]];
denomboxes=RowBox@Flatten@MapThread[{TDd,MakeBoxes[#]}&,{t}];
InterpretationBox[#1,#2,Editable->False]&@@{FractionBox[numboxes,denomboxes],TotalD[expr,t]}]


Unprotect[Dt];
MakeBoxes[Dt[f_Symbol],form:StandardForm]:=InterpretationBox[#1,#2,Editable->False]&@@{RowBox[{"\[DifferentialD]",MakeBoxes[f,form]}],Dt[f]};
MakeBoxes[Dt[f_Symbol,t_Symbol],form:StandardForm]:=InterpretationBox[#1,#2,Editable->False]&@@{FractionBox[RowBox[{"\[DifferentialD]",MakeBoxes[f,form]}],RowBox[{"\[DifferentialD]",MakeBoxes[t,form]}]],Dt[f,t]};
MakeBoxes[Dt[f_Symbol,{t_Symbol,n_Integer}],form:StandardForm]:=InterpretationBox[#1,#2,Editable->False]&@@{FractionBox[RowBox[{SuperscriptBox["\[DifferentialD]",MakeBoxes[n,form]],MakeBoxes[f,form]}],SuperscriptBox[RowBox[{" ","\[VeryThinSpace]\[DifferentialD]",MakeBoxes[t,form]}],MakeBoxes[n,form]]],Dt[f,{t,n}]};
Protect[Dt];


MakeBoxes[AbsoluteD[expr_,t_/;\[Not]VectorQ[t]],form:StandardForm|TraditionalForm]:=
InterpretationBox[#1,#2,Editable->False]&@@{FractionBox[RowBox[{ADu,MakeBoxes[expr,form]}],RowBox[{ADd,MakeBoxes[t,form]}]],AbsoluteD[expr,t]}


MakeBoxes[AbsoluteD[expr_,t:{__}],form:StandardForm|TraditionalForm]:=
Module[{p=Length[t],numboxes,denomboxes},
numboxes=
If[p==1,
RowBox[{ADu,MakeBoxes[expr,form]}],
RowBox[{SuperscriptBox[ADu,ToString[p]],MakeBoxes[expr,form]}]];
denomboxes=RowBox@Flatten@MapThread[{ADd,MakeBoxes[#]}&,{t}];
InterpretationBox[#1,#2,Editable->False]&@@{FractionBox[numboxes,denomboxes],AbsoluteD[expr,t]}]


TensorLabelFormat[args:{_Symbol,_}..]/;Length[{args}]>1:=(TensorLabelFormat@@#&/@{args};)


TensorLabelFormat[label_Symbol,format_]:=
MakeBoxes[label,form:StandardForm|TraditionalForm]:=InterpretationBox[#1,#2,Editable->False]&@@{MakeBoxes[format,form],label}


ClearTensorLabelFormat[args:_Symbol..]/;Length[{args}]>1:=(ClearTensorLabelFormat/@{args};)


ClearTensorLabelFormat[label_Symbol]:=
MakeBoxes[label,form:StandardForm|TraditionalForm]=.


TensorialHelp:=FrontEndExecute[FrontEnd`FrontEndToken["OpenHelpLink",{"paclet:TensorCalculus5",Automatic}]]


CopyRelease[expr_]:=FixedPoint[ReleaseHold,expr]/.x_?(Head[#]===Symbol\[And]Context[#]==="$CellContext`"&):>ToExpression["Global`"<>SymbolName[x]] /.{PartialDH->PartialD,CovariantDH->CovariantD,AbsoluteDH->AbsoluteD,TotalDH->TotalD,LieDH->LieD,FullForm->Identity}


ToArrayValues[][expr_]:=ToArrayValues[Automatic][expr]


ToArrayValues[][expr_]:=
Module[{work,labels,valuerules,subroutine},

subroutine[work_]:=
Module[{},
labels=Cases[work,Tensor[label_,___]->label,{0,\[Infinity]}];
valuerules=TensorValueRules@@labels;
If[Head[valuerules]===List,work/.valuerules,work]];

work=subroutine[expr//EinsteinSum[]]//EinsteinArray[];

FixedPoint[subroutine,work,5]
]


SyntaxInformation[ContractArray]={"ArgumentsPattern"->{_,__}};
ContractArray[tt_,inxs:({_,_}..)]:=Nest[Tr[#1,Plus,2]&,Transpose[tt,
(* Calculate the destination slots of each level *)
Block[{x=Range[TensorRank[tt]],cindices=Join[inxs]},x[[Join[cindices,Complement[x,cindices]]]]=x;
x]],
Length[{inxs}]]


tensordotguide[term_]:=
Module[
{dummies,slots,newname,context},
dummies=Part[term//ParseTermIndices,1];
slots=Part[term//ExtractTermSlots,2];
slots=Select[#,\[Not]MatchQ[Part[#,2],Alternatives@@dummies]&]&/@slots;
slots=Function[slotlist,Sort[slotlist,OrderedQ[{RawIndex[Part[#1,2]],RawIndex[Part[#2,2]]}]&]][Flatten[slots,1]];
context=Context@@{Part[slots,1,1]};
newname=Union[First/@slots];
newname=Symbol[context<>StringJoin@@(SymbolName/@newname)];
slots=slots//.{a_,b_,c:(1|-1)}->{newname,b,c};
SlotsToTensor[slots]
]


SyntaxInformation[DotTensorFactors]={"ArgumentsPattern"->{{__},_.}};
DotTensorFactors[order_List,displayguide_:True][term_]/;Length[Flatten[order]]==Length[term]\[And]Head[term]===Times:=
Module[{wlist={},i},
Do[AppendTo[wlist,Part[term,Part[order,i]]],{i,1,Length[order]}];
If[displayguide,Print[Panel[Style[Dot@@tensordotguide/@wlist,14,Bold],"Expansion Order"]]];
Dot@@wlist
]


SyntaxInformation[ExpandDotArray]={"ArgumentsPattern"->{__}};
ExpandDotArray[tensorpattern_,transposeorder_:Automatic][expr_]:=
Module[{wtranspose},
wtranspose=If[transposeorder===Automatic,Range[NDim],transposeorder];
expr/.t:tensorpattern:>MatrixForm[Transpose[ToArrayValues[][t],wtranspose]]
]


SyntaxInformation[DotOperate]={"ArgumentsPattern"->{_,_}};
DotOperate[position_Integer?Positive,operation_][term_]:=term//MapLevelParts[MatrixForm[operation[First[Part[#,1]],First[Part[#,2]]]]&,{{position,position+1}}]


baseindexpattern=(_Integer|_Symbol);
flavoredbasepattern={_?IndexFlavorQ,{baseindexpattern..}}


SyntaxInformation[DeclareBaseIndices]={"ArgumentsPattern"->{__}};
DeclareBaseIndices[generalbaselist:{baseindexpattern..},flavoredbases:flavoredbasepattern...]:=
Module[{},
BaseIndices=generalbaselist;
CompleteBaseIndices={generalbaselist,flavoredbases};
 NDim=Length[generalbaselist];
baseflavors={flavoredbases};
allBaseIndices=generalbaselist;
Scan[(allBaseIndices=Union[allBaseIndices,Part[#,2]])&,baseflavors,{1}]
]


SyntaxInformation[GetBaseIndices]={"ArgumentsPattern"->{_}};
GetBaseIndices[index_]:=
Module[{flavor=GetIndexFlavor[index],work=BaseIndices},
If[flavor===Identity,Return[BaseIndices]];
Scan[If[Part[#,1]===flavor,work=Part[#,2];Return[]]&,baseflavors,{1}];
work
]


SyntaxInformation[BaseIndexQ]={"ArgumentsPattern"->{_}};
BaseIndexQ[index_]:=
MemberQ[GetBaseIndices[index], RawIndex[index]]


SyntaxInformation[CircleEvalRule]={"ArgumentsPattern"->{__}};
CircleEvalRule=
{CircleTimes[vects__][args__]/;Length[{vects}]==Length[{args}]:>Module[{scalar,tensor},
scalar=Times@@Select[MapThread[Dot,{{vects},{args}}], FreeQ[#,Null]&];
If[FreeQ[{args},Null],
tensor=1,
tensor=CircleTimes@@First@Transpose@Select[Transpose[{{vects},{args}}],#[[2]]==Null&];
tensor=tensor/.CircleTimes[a_]->a];
scalar tensor],
(v:Tensor[_,{_},{_}])[arg_]:>v.arg};


SyntaxInformation[EvaluateSlots]={"ArgumentsPattern"->{_,_}};
EvaluateSlots[b_Symbol,g_Symbol][expr_]:=
Module[{bu,bd,work},
{bu,bd}={Function[i,b[Global`u[i]]],Function[i,b[Global`d[i]]]};
work=(expr/.head_?(\[Not]FreeQ[#,CircleTimes]&)[args___]:>(ExpandAll[head[args]]//PushOnto[{args},{CircleTimes[__]}])/.CircleEvalRule);
work=(work//LinearBreakout[Dot][bu[_],bd[_]])/.BasisDotProductRules[b,g];
work=work//MetricSimplify[g];
work/.CircleTimes[x_]->x
];


SyntaxInformation[BasisDotProductRules]={"ArgumentsPattern"->{_,_}};
BasisDotProductRules[b_Symbol,g_Symbol]:={Tensor[b,{i_},{Void}].Tensor[b,{j_},{Void}]->Tensor[g,{i,j},{Void,Void}],Tensor[b,{Void},{i_}].Tensor[b,{Void},{j_}]->Tensor[g,{Void,Void},{i,j}],Tensor[b,{i_},{Void}].Tensor[b,{Void},{j_}]->Tensor[g,{i,Void},{Void,j}],Tensor[b,{Void},{i_}].Tensor[b,{j_},{Void}]->Tensor[g,{Void,j},{i,Void}]}


SyntaxInformation[ReverseBasisDotProductRules]={"ArgumentsPattern"->{_,_}};
ReverseBasisDotProductRules[b_Symbol,g_Symbol]:={Tensor[g,{i_,j_},{Void,Void}]->Tensor[b,{i},{Void}].Tensor[b,{j},{Void}],Tensor[g,{Void,Void},{i_,j_}]->Tensor[b,{Void},{i}].Tensor[b,{Void},{j}],Tensor[g,{i_,Void},{Void,j_}]->Tensor[b,{i},{Void}].Tensor[b,{Void},{j}],Tensor[g,{Void,j_},{i_,Void}]->Tensor[b,{Void},{i}].Tensor[b,{j},{Void}]};


SyntaxInformation[EvaluateDotProducts]={"ArgumentsPattern"->{__}};
EvaluateDotProducts[e_,g_,metricsimplify_:True][expr_]:=
expr/.
{Dot[0,_]->0,
Dot[_,0]->0,dp:Dot[_,_]:>((dp//LinearBreakout[Dot][Tensor[e,{_},{Void}],Tensor[e,{Void},{_}]])/.BasisDotProductRules[ e,g]//If[metricsimplify,MetricSimplify[g],Identity])}


SyntaxInformation[ConstructDirectProduct]={"ArgumentsPattern"->{__}};
ConstructDirectProduct[a_. b:CircleTimes[__]]:=
Module[{work,heads,newhead,arglist},
work=List@@b;
heads=Head/@work;
arglist=Replace[#,f_[args__]->args]&/@work;
newhead=CircleTimes@@heads;
newhead=newhead//LinearBreakout[CircleTimes][CircleTimes[__]];
newhead=newhead/.expr:CircleTimes[__]:>Flatten[expr];
a (newhead@@arglist)]


SyntaxInformation[GenerateBasisTensors]={"ArgumentsPattern"->{_,_}};
GenerateBasisTensors[g_Symbol,configuration_String]:=
Module[{configs,indices,basistensor},
configs=Characters[configuration];
If[\[Not]And@@((#==="d")\[Or](#==="u")&/@configs),Message[GenerateBasisTensors::config,configuration];Abort[]];
indices=Table[Unique["i"],{Length[configs]}];
basistensor=CircleTimes@@MapThread[g[Symbol[#1][#2]]&,{configs,indices}];
basistensor//ArrayExpansion[indices]//Flatten
]


UnsortedUnion[x_]:=Module[{f},f[y_]:=(f[y]=Sequence[];y);f/@x]


IndexParsingRules={};


SyntaxInformation[ParseTermIndices]={"ArgumentsPattern"->{_}};
ParseTermIndices[term_]:=
Module[
{wterms=term,slotsort,uplist,downlist,slotorder,badlist,dummylist,scalar,tlab},

slotsort[list_]:=Sort[list,Part[Position[slotorder,#1],1,1]<=Part[Position[slotorder,#2],1,1]&];

(* Convert the term to a list of tensors *)
wterms=wterms/.a_Function:>If[Length[a]<3,Last[a],Part[a,2]];
If[MatchQ[IndexParsingRules, (Rule|RuleDelayed)[_,_]|{ (Rule|RuleDelayed)[_,_]..}],
wterms=wterms//.IndexParsingRules];

wterms=wterms/.
(TotalD|AbsoluteD|LieD)[t_,___]->t;
wterms=wterms
//.HoldPattern[PartialD[t_,dvars_]]:>t Tensor[tlab,Table[Void,{Length[Flatten[{dvars}]]}],Flatten[{dvars}]];

wterms=wterms
//.HoldPattern[CovariantD[t_,updvars_,dvars_]]:>t Tensor[tlab,updvars,dvars];

wterms=wterms/.HoldPattern[PartialD[_][t_,dvars_]]:>t Times@@Cases[dvars,Tensor[l_,ups_,downs_]->Tensor[l,downs,ups],{0,1}];

wterms=wterms/.
Tensor[t_]:>If[FreeQ[{t},Plus],t ,scalar];
wterms=wterms/.t_Tensor[___]->t;

wterms=wterms/.
(Dot|CircleTimes|TensorForms1`TensorialForms`Wedge)->Times/.Tensor[_]->1;

wterms=If[Head[wterms]===Times,List@@wterms,{wterms}];
wterms=Flatten[If[MatchQ[#, Power[a_Tensor,n_Integer?Positive]],Table[First[#],{Last[#]}],#]&/@wterms];
wterms=If[Head[#]===Tensor,#,Unevaluated[Sequence[]]]&/@wterms;
If[wterms==={},Return[{{},{{},{}},{}}]];

(* Generate the indices in slotorder *)
slotorder=(#/.Tensor[_,ups_,downs_]:>(Flatten@Transpose[{ups,downs}]/.Void->Sequence[]))&/@wterms;
slotorder=UnsortedUnion@Join@@slotorder;

(* Extract the up and down indices *)
uplist=Flatten@(wterms/.Tensor[_,ups_,_]->ups)/.Void->Sequence[];
uplist=(If[BaseIndexQ[#],Unevaluated[Sequence[]],#]&/@uplist);
downlist=Flatten@(wterms/.Tensor[_,_,downs_]->downs)/.Void->Sequence[];
downlist=(If[BaseIndexQ[#],Unevaluated[Sequence[]],#]&/@downlist);

(* Extract the bad indicies. They occur more than once in the uplist or in the downlist *)
badlist=Union@Flatten@{Cases[Split[Sort@uplist],t_List/;Length[t]>1],Cases[Split[Sort@downlist],t_List/;Length[t]>1]};

(* Remove bad indices from uplist and downlist *)
uplist=Complement[uplist,badlist];
downlist=Complement[downlist,badlist];

(* Extract the dummy indices and remove them from uplist and downlist*)
dummylist =Intersection[uplist,downlist];
uplist=Complement[uplist,dummylist];
downlist=Complement[downlist,dummylist];

{slotsort@dummylist,slotsort/@{uplist,downlist},badlist}
]


SyntaxInformation[RawIndex]={"ArgumentsPattern"->{_}};
RawIndex[index_]:=
Switch[index,
(f_?IndexFlavorQ)[_],First[index],
_Symbol|_Integer,index,
_,Message[RawIndex::notindex,index];index]


SyntaxInformation[ExtractFreeIndices]={"ArgumentsPattern"->{_}};
ExtractFreeIndices[expr_]:=
Module[{terms,updowns,matched,badindices,nobadindices},
terms=Flatten[{Distribute[expr,Plus,Times]/.Equal|Unequal|Less|Greater|LessEqual|GreaterEqual->List/.Plus->List}];
terms=ParseTermIndices/@terms;
terms=Transpose[terms];
badindices=Take[terms,-1];
terms=Part[terms,2];
terms=MapAt[Sort,#,{{1},{2}}]&/@terms;
updowns=First[terms];
nobadindices=Length[Flatten[badindices]]==0;
matched=And@@(updowns===#&/@terms);
If[nobadindices\[And]matched,updowns,Message[FreeIndices::notmatched];False]
]


SyntaxInformation[ExtractDummyIndices]={"ArgumentsPattern"->{_}};
ExtractDummyIndices[expr_]:=
Module[{terms,dummies,updowns,matched,badindices,nobadindices},
terms=Flatten[{Distribute[expr,Plus,Times]/.Equal|Unequal|Less|Greater|LessEqual|GreaterEqual->List/.Plus->List}];
terms=ParseTermIndices/@terms;
terms=Transpose[terms];
dummies=Take[terms,1]//Flatten//Union;
badindices=Take[terms,-1];
terms=Part[terms,2];
terms=MapAt[Sort,#,{{1},{2}}]&/@terms;
updowns=First[terms];
nobadindices=Length[Flatten[badindices]]==0;
matched=And@@(updowns===#&/@terms);
If[nobadindices\[And]matched,dummies,Message[FreeIndices::notmatched];False]
]


SyntaxInformation[SymbolicIndexQ]={"ArgumentsPattern"->{_}};
SymbolicIndexQ[i_]:=
Module[{ISymbol},
ISymbol[s_]:=Head[s]===Symbol\[And]\[Not]BaseIndexQ[s];
MatchQ[i,( _?ISymbol)|((_?IndexFlavorQ)[_?ISymbol])]
]


jval[i_,j_,array_,pos_]:=
Module[{jnew,newpos},
newpos=First[pos];
jnew=If[Length[newpos]==1,j,array[[First[newpos]]]/.i->j];
{jnew,First[newpos]}]


SyntaxInformation[RaiseIndex]={"ArgumentsPattern"->{_,_}};
RaiseIndex[i_,j_][expr_/;\[Not]MatchQ[Head[expr],Tensor|CovariantD]]:=expr//.t:(Tensor|CovariantD)[_,_,downs_/;\[Not]FreeQ[downs,i]]:>RaiseIndex[i,j][t]


RaiseIndex[i_,j_][t_Tensor|t_CovariantD]:=
Module[{pos,ups,downs,jnew,head=Head[t]},
{ups,downs}=List@@t[[{2,3}]];
pos=Position[downs,i];
If[pos==={},Message[RaiseIndex::noindex,i,t];Abort[]];
{jnew,pos}=jval[i,j,downs,pos];
downs[[pos]]=Void;
ups[[pos]]=jnew;
head[First[t],ups,downs]
]


SyntaxInformation[LowerIndex]={"ArgumentsPattern"->{_,_}};
LowerIndex[i_,j_][expr_/;\[Not]MatchQ[Head[expr],Tensor|CovariantD]]:=expr//.t:(Tensor|CovariantD)[_,ups_/;\[Not]FreeQ[ups,i],_]:>LowerIndex[i,j][t]


LowerIndex[i_,j_][t_Tensor|t_CovariantD]:=
Module[{pos,ups,downs,jnew,head=Head[t]},
{ups,downs}=List@@t[[{2,3}]];
pos=Position[ups,i];
If[pos==={},Message[LowerIndex::noindex,i,t];Abort[]];
{jnew,pos}=jval[i,j,ups,pos];
ups[[pos]]=Void;
downs[[pos]]=jnew;
head[First[t],ups,downs]
]


SyntaxInformation[ReplaceIndex]={"ArgumentsPattern"->{_,_}};
ReplaceIndex[i_,j_][expr_/;\[Not]MatchQ[Head[expr],Tensor|CovariantD]]:=expr//.t:(Tensor|CovariantD)[_,ups_,downs_]/;\[Not]FreeQ[Union[ups,downs],i]:>ReplaceIndex[i,j][t]


ReplaceIndex[i_,j_][t_Tensor|t_CovariantD]:=
Module[{pos,ups,downs,posups,posdowns,jnew,head=Head[t]},
{ups,downs}=List@@t[[{2,3}]];
posups=Position[ups,i];
posdowns=Position[downs,i];
If[posups==={}\[And]posdowns==={},Message[ReplaceIndex::noindex,i,t];Abort[]];
If[posups=!={},{jnew,pos}=jval[i,j,ups,posups];
ups[[pos]]=jnew;];
If[posdowns=!={},{jnew,pos}=jval[i,j,downs,posdowns];
downs[[pos]]=jnew;];
head[First[t],ups,downs]
]


basicIndexPatterns=
{{2,{2|3,_}, Tensor[_,_List,_List]},{1,{2},HoldPattern[PartialD[_,i_]/;Head[i]=!=List]},
{2,{2,_},HoldPattern[PartialD[_,{__}]]},{1,{2},HoldPattern[CovariantD[_,i_]/;Head[i]=!=List]},
{2,{2|3,_},HoldPattern[CovariantD[_,{__},{__}]]}}
NewIndexChangePatterns={};


indextest[i_]:=
Module[{good},
Off[RawIndex::notindex];
good=SymbolicIndexQ[i]\[Or]BaseIndexQ[i];
On[RawIndex::notindex];
good];


indexreplacement[expr_,{oldindex_,newindex_},symboliconly_,indexspecs_]:=
Module[
{putativepositions,actualpositions,positiontest},

(* Determines if a putativeposition is actually an index position *)
positiontest[position_]:=
Module[{testpattern},
(* Tests a putativeposition against a particular index specification *)
testpattern[pos_][{ndrop_Integer?Positive,droppattern_,pattern_}]:=
Module[{workposition,droppedpositions},
If[ndrop>Length[pos],Return[False]];
workposition=Drop[position,-ndrop];
droppedpositions=Take[position,-ndrop];
MatchQ[Part[expr,Sequence@@workposition],pattern]\[And]MatchQ[droppedpositions,droppattern]
];
Or@@(testpattern[position]/@indexspecs)
];

putativepositions=Position[expr,oldindex];
If[(putativepositions==={})\[Or](symboliconly\[And]\[Not]SymbolicIndexQ[oldindex]),Return[{}]];
actualpositions=If[positiontest[#],#,Unevaluated[Sequence[]]]&/@putativepositions;
Flatten[Outer[List,{newindex},actualpositions,1,1],1]
]


SyntaxInformation[IndexChange]={"ArgumentsPattern"->{_,_.,_.}};
IndexChange[pair:{_?indextest,_?indextest},sign:(1|-1):1,symboliconly:(True|False):True][expr_]:=IndexChange[{pair},sign,symboliconly][expr];


IndexChange[pairs:{{_?indextest,_?indextest}..},sign:(1|-1):1,symboliconly:(True|False):True][expr_]:=
Module[
{replacetable,npairs=Length[pairs],i,completeindexspecs},
completeindexspecs=Join[basicIndexPatterns,NewIndexChangePatterns];
replacetable=
Flatten[Table[indexreplacement[expr,Part[pairs,i],symboliconly,completeindexspecs],{i,1,npairs}],1];
If[Length[replacetable]==0,Return[expr]];
replacetable=Transpose[replacetable];
sign ReplacePart[expr,Part[replacetable,1],Part[replacetable,2],Partition[Range[Length[Part[replacetable,1]]],1]]
]


tensorindexpositions[expr_,indx_]:=
Module[{p,pos1,pos2,ppos1,ppos2,work},
pos1=Position[expr,Tensor[_,a__]/;\[Not]FreeQ[{a},indx]];
ppos1=p@@#&/@pos1;
pos2=Position[expr,indx];
ppos2=p@@#&/@pos2;
work=Outer[{#1,#2}&,ppos1,ppos2]/.p->List;
work=Flatten[work,1];
Select[work,#[[1]]===Take[#[[2]],Length[#[[1]]]]&]
]


SyntaxInformation[UpDownSwap]={"ArgumentsPattern"->{_}};
UpDownSwap[indx_][expr_]:=
Module[{q1=Unique[q],q2=Unique[q],pos,wexpr,swap},

swap[i_,pos_,j_][wexpr_]:=
Module[{updown},
updown=Part[Last[pos],Length[First[pos]]+1];
Switch[updown,
2,LowerIndex[i,j][Part[wexpr,Sequence@@First[pos]]],
3,RaiseIndex[i,j][Part[wexpr,Sequence@@First[pos]]]]
];

Switch[Head[expr],
List,UpDownSwap[indx]/@expr,
Equal|Less|Greater|LessEqual|GreaterEqual,UpDownSwap[indx]/@expr,
Plus,UpDownSwap[indx]/@expr,
_,
If[\[Not]MemberQ[First[ParseTermIndices[expr]], indx],Return[expr]];
wexpr=Hold@@{expr};
pos=tensorindexpositions[wexpr,indx];
wexpr=ReplacePart[wexpr,q1,Last[First[pos]]];
wexpr=ReplacePart[wexpr,q2,Last[Last[pos]]];

wexpr=ReplacePart[wexpr,swap[q1,First[pos],indx][wexpr],First[First[pos]]];
wexpr=ReplacePart[wexpr,swap[q2,Last[pos],indx][wexpr],First[Last[pos]]];
First[wexpr]
]
]


SyntaxInformation[SumExpansion]={"ArgumentsPattern"->{__}};
SumExpansion[indices__][expr_]/;And@@(Head[#]=!=List\[And]#=!=Automatic&/@{indices}):=SumExpansion[{indices}][expr]


SumExpansion[indices__,baseindices_List][expr_]/;And@@(Head[#]=!=List\[And]#=!=Automatic&/@{indices}):=SumExpansion[{indices},baseindices][expr]


SumExpansion[indices_List,baseindices_:Automatic][inexpr_]/;MatchQ[baseindices,Automatic|{(_Integer|_Symbol)..}|{{(_Integer|_Symbol)..}..}]:=
Module[{expr=ExpandAll[inexpr]},
Switch[Head[expr],
List,SumExpansion[indices,baseindices]/@expr,
Equal|Unequal|Less|Greater|LessEqual|GreaterEqual,SumExpansion[indices,baseindices]/@expr,
(* Power,SumExpansion[indices,baseindices]/@First[expr], *)
Plus,SumExpansion[indices,baseindices]/@expr,
_,SumExpansion2[indices,baseindices][expr]]
]


SumExpansion2[indices_List,baseindices_:Automatic][inexpr_]/;MatchQ[baseindices,Automatic|{(_Integer|_Symbol)..}|{{(_Integer|_Symbol)..}..}]:=
Module[
{expr=ExpandAll[inexpr],idx,inindex,wbaseindices,indexstructure,wstructure,replace,uq,q,uqreplace},

wbaseindices=If[VectorQ[baseindices],{baseindices},baseindices];

indexstructure=
Module[{index,bases,subbases},
Table[
index=Part[indices,idx];
bases=GetBaseIndices[index];
subbases=If[Length[wbaseindices]>=idx,Part[wbaseindices,idx],bases];
If[\[Not](Intersection[subbases,bases]===Sort[subbases]),Message[SumArrayExpansion::subset,subbases,bases];Abort[],
bases=subbases];
{index,bases},{idx,1,Length[indices]}]
];

inindex[i_]:=(Count[{expr},
Tensor[_,up_/;\[Not]FreeQ[up, i,1],down_]|
Tensor[_,up_,down_/;\[Not]FreeQ[down,  i,1]]|
HoldPattern[PartialD[_,i]]|
HoldPattern[PartialD[_,{___,i,___}]]|
HoldPattern[CovariantD[_,i]]|
HoldPattern[CovariantD[_,{___,i,___}]],\[Infinity],Heads->True]>0\[And]\[Not]BaseIndexQ[i]);

replace[i_,newindex_]:=
Switch[Head[i],
_?IndexFlavorQ,Head[i][newindex],
_,newindex];

uqreplace[i_]:=
Switch[Head[i],
_?IndexFlavorQ,Head[i][q],
_,q];

wstructure=Select[indexstructure,inindex[First[#]]&];

Fold[Plus@@Table[(#1//IndexChange[{First[#2],uq=uqreplace[First[#2]]}])/.uq->replace[First[#2],Part[Last[#2],idx]],{idx,1,Length[Last[#2]]}]&,expr,wstructure]
]


SyntaxInformation[ArrayExpansion]={"ArgumentsPattern"->{__}};
ArrayExpansion[indices__][expr_]/;And@@(Head[#]=!=List\[And]#=!=Automatic&/@{indices}):=ArrayExpansion[{indices}][expr]


ArrayExpansion[indices__,baseindices_List][expr_]/;And@@(Head[#]=!=List\[And]#=!=Automatic&/@{indices}):=ArrayExpansion[{indices},baseindices][expr]


ArrayExpansion[indices_List,baseindices_:Automatic][expr_]/;MatchQ[baseindices,Automatic|{(_Integer|_Symbol)..}|{{(_Integer|_Symbol)..}..}]:=
Module[
{idx,inindex,wbaseindices,indexstructure,wstructure,replace,uq,q,uqreplace},

wbaseindices=If[VectorQ[baseindices],{baseindices},baseindices];

indexstructure=
Module[{index,bases,subbases},
Table[
index=Part[indices,idx];
bases=GetBaseIndices[index];
subbases=If[Length[wbaseindices]>=idx,Part[wbaseindices,idx],bases];
If[\[Not](Intersection[subbases,bases]===Sort[subbases]),Message[SumArrayExpansion::subset,subbases,bases];Abort[],
bases=subbases];
{index,bases},{idx,1,Length[indices]}]
];

inindex[i_]:=(Count[{expr},
Tensor[_,up_/;\[Not]FreeQ[up, i,1],down_]|
Tensor[_,up_,down_/;\[Not]FreeQ[down,  i,1]]|
HoldPattern[PartialD[_,i]]|
HoldPattern[PartialD[_,{___,i,___}]]|
HoldPattern[CovariantD[_,i]]|
HoldPattern[CovariantD[_,{___,i,___}]],\[Infinity],Heads->True]>0\[And]\[Not]BaseIndexQ[i]);

replace[i_,newindex_]:=
Switch[Head[i],
_?IndexFlavorQ,Head[i][newindex],
_,newindex];

uqreplace[i_]:=
Switch[Head[i],
_?IndexFlavorQ,Head[i][q],
_,q];

wstructure=Select[indexstructure,inindex[First[#]]&];

Fold[List@@Table[(#1//IndexChange[{First[#2],uq=uqreplace[First[#2]]}])/.uq->replace[First[#2],Part[Last[#2],idx]],{idx,1,Length[Last[#2]]}]&,expr,Reverse[wstructure]]
]


SyntaxInformation[EinsteinSum]={"ArgumentsPattern"->{_.}};
EinsteinSum[][expr_]:=EinsteinSum[Automatic][expr]


EinsteinSum[baseindices_:Automatic][inexpr_]:=
Module[{sumindices,expr=ExpandAll[inexpr]},
Switch[Head[expr],
List,EinsteinSum[baseindices]/@expr,
Equal|Unequal|Less|Greater|LessEqual|GreaterEqual,EinsteinSum[baseindices]/@Distribute[expr,Plus,Times],
(* Power,EinsteinSum[baseindices]/@First[expr], *)
Plus,EinsteinSum[baseindices]/@expr,
_, 
sumindices=First[ParseTermIndices[expr]];
If[Length[sumindices]==0,Return[expr]];
SumExpansion[sumindices, baseindices][expr]]
]


SyntaxInformation[EinsteinArray]={"ArgumentsPattern"->{_.}};
EinsteinArray[][expr_]:=EinsteinArray[Automatic][expr]


EinsteinArray[baseindices_:Automatic][expr_]:=
Module[{freeindices},
freeindices=ExtractFreeIndices[expr];
If[freeindices===False,Abort[]];
If[Length[Flatten[freeindices]]==0,Return[expr]];
freeindices=Sort[Flatten[freeindices],OrderedQ[{RawIndex[#1],RawIndex[#2]}]&];
ArrayExpansion[freeindices, baseindices][expr]
]


SyntaxInformation[PartialSum]={"ArgumentsPattern"->{_,_}};
PartialSum[baseindex_,newindices_List][expr_]:=
Module[
{baseflavor=GetIndexFlavor[baseindex],rawbase=RawIndex[baseindex],flavoredbases,baseexpand,freeindices,dummyindices,numdummy,array,newwork},

baseexpand[term_]:=
Module[{iarray=1,gen},

gen[idepth_,indices_]:=
Module[{},
If[idepth>numdummy,
array=ReplacePart[array,indices,iarray++],
gen[idepth+1,indices];
gen[idepth+1,ReplacePart[indices,baseindex,idepth]]]
];

gen[1,dummyindices];
Plus@@(term/.Thread/@MapThread[dummyindices->#&,{array}])
];

Switch[Head[expr],
List,PartialSum[baseindex,newindices]/@expr,
Equal|Unequal|Less|Greater|LessEqual|GreaterEqual,PartialSum[baseindex,newindices]/@expr,
Plus,PartialSum[baseindex,newindices]/@expr,
_,
flavoredbases=GetBaseIndices[baseindex];
If[\[Not]MemberQ[flavoredbases,rawbase],Message[PartialSum::baseindex,rawbase,flavoredbases];Abort[]];

{dummyindices,freeindices}={Part[#,1],Flatten[Part[#,2]]}&[ParseTermIndices[expr]];
dummyindices=Select[dummyindices,GetIndexFlavor[#]===baseflavor&];
freeindices=Select[freeindices,GetIndexFlavor[#]===baseflavor&];

newwork=Complement[newindices,freeindices];
numdummy=Length[dummyindices];

If[Length[newwork]<numdummy,Message[PartialSum::newindices,newwork,freeindices,dummyindices];Abort[]];

array=Table[{0,0},{2^numdummy}];
baseexpand[expr]/.Thread[dummyindices->Take[newwork,Length[dummyindices]]]]
]


SyntaxInformation[PartialArray]={"ArgumentsPattern"->{_,_}};
PartialArray[baseindex_,newindices_List][expr_]:=
Module[
{baseflavor=GetIndexFlavor[baseindex],rawbase=RawIndex[baseindex],flavoredbases,baseexpand,freeindices,dummyindices,numfree,array,newwork, checkfree},

checkfree[wexpr_]:= If[ExtractFreeIndices[wexpr]===False,Abort[]]; 

baseexpand[term_]:=
Module[{iarray=1,gen},

gen[idepth_,indices_]:=
Module[{},
If[idepth>numfree,
array=ReplacePart[array,indices,iarray++],
gen[idepth+1,indices];
gen[idepth+1,ReplacePart[indices,baseindex,idepth]]]
];

gen[1,freeindices];
(term/.Thread/@MapThread[freeindices->#&,{array}])//Reverse
];



Switch[Head[expr],
List,PartialArray[baseindex,newindices]/@expr,
Equal|Unequal|Less|Greater|LessEqual|GreaterEqual,checkfree[expr];PartialArray[baseindex,newindices]/@expr,
Plus,checkfree[expr];PartialArray[baseindex,newindices]/@expr,
_,
flavoredbases=GetBaseIndices[baseindex];
If[\[Not]BaseIndexQ[baseindex],Message[PartialSum::baseindex,rawbase,flavoredbases];Abort[]];

{dummyindices,freeindices}={Part[#,1],Flatten[Part[#,2]]}&[ParseTermIndices[expr]];
dummyindices=Select[dummyindices,GetIndexFlavor[#]===baseflavor&];
freeindices=Select[freeindices,GetIndexFlavor[#]===baseflavor&];

newwork=Complement[newindices,dummyindices];
numfree=Length[freeindices];
If[Length[newwork]<numfree,Message[PartialArray::newindices,newwork,dummyindices,freeindices];Abort[]];

array=Table[{0,0},{2^numfree}];
baseexpand[expr]/.Thread[freeindices->Take[newwork,numfree]]]
]


SyntaxInformation[EinsteinArgument]={"ArgumentsPattern"->{_,_.}};
EinsteinArgument[x_,func_:Automatic][expr_]:=
Switch[func,
Automatic,expr/.
{(f_)[Tensor[x,{a_},{Void}]]:>f@@EinsteinArray[][Tensor[x,{a},{Void}]],
(f_)[Tensor[x,{a_},{Void}][args___]]:>f@@EinsteinArray[][Tensor[x,{a},{Void}][args]],

(f_)[Tensor[x,{Void},{a_}]]:>f@@EinsteinArray[][Tensor[x,{Void},{a}]],
(f_)[Tensor[x,{Void},{a_}][args___]]:>f@@EinsteinArray[][Tensor[x,{Void},{a}][args]]},

_,expr/.
{(f:func)[Tensor[x,{a_},{Void}]]:>f@@EinsteinArray[][Tensor[x,{a},{Void}]],
(f:func)[Tensor[x,{a_},{Void}][args___]]:>f@@EinsteinArray[][Tensor[x,{a},{Void}][args]],

(f:func)[Tensor[x,{Void},{a_}]]:>f@@EinsteinArray[][Tensor[x,{Void},{a}]],
(f:func)[Tensor[x,{Void},{a_}][args___]]:>f@@EinsteinArray[][Tensor[x,{Void},{a}][args]]}]


SyntaxInformation[DeclareIndexFlavor]={"ArgumentsPattern"->{__}};
DeclareIndexFlavor[flavor1:{_Symbol,_},flavors:{_Symbol,_}..]:=(DeclareIndexFlavor/@{flavor1,flavors};)


DeclareIndexFlavor[{flavorname_Symbol,flavorform_}]:=Module[{},IndexFlavors=IndexFlavors/. {flavorname,_}->Sequence[];IndexFlavors=Join[IndexFlavors,{{flavorname,flavorform}}];Which[MatchQ[Head[flavorform],RGBColor|GrayLevel],\!\(\*
TagBox[
FormBox[
RowBox[{"flavorname", "[", "i_", "]"}],
StandardForm],
Format]\):=Style[i,FontColor->flavorform],True,\!\(\*
TagBox[
FormBox[
RowBox[{"flavorname", "[", "i_", "]"}],
StandardForm],
Format]\):=flavorform[i]];]


SyntaxInformation[ToFlavor]={"ArgumentsPattern"->{_,_.}};
ToFlavor[toflavor_,fromflavor_:Identity][expr_]:=
Module[{switchQ,replacement},
If[toflavor=!=Identity\[And]Count[IndexFlavors, {toflavor,_}]==0,Message[Flavor::notflavor,toflavor];Return[expr]];

switchQ[indx_]:=
GetIndexFlavor[indx]===fromflavor\[And]indx=!=Void\[And](Head[RawIndex[indx]]===Integer\[Or]\[Not]BaseIndexQ[indx]);

replacement=
If[switchQ[#],
Which[
fromflavor===Identity,toflavor@#,
True,toflavor@@#],
Identity@#]&;

expr/.Tensor[label_,upindices_,downindices_]:>Tensor[label,replacement/@upindices,replacement/@downindices]/.
HoldPattern[PartialD[t_,indices_List]]:>PartialD[t,replacement/@Flatten[{indices}]]/.
HoldPattern[PartialD[t_,index_]]:>PartialD[t,replacement[index]]/.
HoldPattern[CovariantD[t_,upindices_,downindices_List]]:>CovariantD[t,replacement/@Flatten[{upindices}],replacement/@Flatten[{downindices}]]
]


SyntaxInformation[ClearIndexFlavor]={"ArgumentsPattern"->{__}};
ClearIndexFlavor[args:{{_Symbol,_}..}]:=(ClearIndexFlavor/@args;)


ClearIndexFlavor[{flavor_Symbol,_}]:=ClearIndexFlavor[flavor]


ClearIndexFlavor[flavor1_Symbol,flavors__Symbol]:=(ClearIndexFlavor/@{flavor1,flavors};)


ClearIndexFlavor[flavor_Symbol]:=
Module[{},
If[Count[IndexFlavors, {flavor,_}]==0,Message[Flavor::notflavor,flavor];Abort[]];
IndexFlavors=IndexFlavors/.{flavor,_}->Sequence[];
Format[flavor[i_]]=.
]


SyntaxInformation[IndexFlavorQ]={"ArgumentsPattern"->{_}};
IndexFlavorQ[flavor_]:=MemberQ[IndexFlavors, {flavor,_}]


SyntaxInformation[GetIndexFlavor]={"ArgumentsPattern"->{_}};
GetIndexFlavor[indx_]:=
Module[{head=Head[indx]},
Switch[head,
Symbol|Integer,Identity,
_,If[IndexFlavorQ[head],head,$Failed]]]


SyntaxInformation[TensorSimplify]={"ArgumentsPattern"->{_}};
TensorSimplify[expr_]/;MatchQ[Head[expr],List|Equal|Less|Greater|LessEqual|GreaterEqual|Unequal]:=TensorSimplify/@expr


TensorSimplify[expr_]:=
Module[{wexpr=Expand[expr],termpatterns,standardpattern,standardterm,k,dum,hit=False},
Off[RawIndex::notindex];

(* Reduce each term to a pattern with dummy index symbols in low order slots *)
standardpattern[term_]:=
Module[{wterm=term,dummylist,freelist,workdummies,workfree,ndummies,f,g},
dummylist=First[ParseTermIndices[term]];
freelist=Flatten[Part[ParseTermIndices[term],2]];
ndummies=Length[dummylist];
If[ndummies==0,Return[Sequence[]]];
workdummies=f/@dummylist;
workfree=g/@freelist;
wterm=IndexChange[Transpose[{dummylist,workdummies}]][wterm];
If[Length[freelist]>0,wterm=IndexChange[Transpose[{freelist,workfree}]][wterm]];
wterm=wterm//SymmetrizeSlots[]//SymmetrizePattern[];
wterm=wterm/.Thread[workfree->freelist];
wterm=wterm/.Thread[workdummies->Table[dum[Unique[i]],{ndummies}]]
];

(* Reduce each term to a form with dummy index symbols in low order slots *)
standardterm[term_]:=
Module[{wterm=term,dummylist,freelist,workdummies,workfree,ndummies,f,g},
dummylist=First[ParseTermIndices[term]];
freelist=Flatten[Part[ParseTermIndices[term],2]];
ndummies=Length[dummylist];
If[ndummies==0,Return[term]];
workdummies=f/@dummylist;
workfree=g/@freelist;
wterm=IndexChange[Transpose[{dummylist,workdummies}]][wterm];
If[Length[freelist]>0,wterm=IndexChange[Transpose[{freelist,workfree}]][wterm]];
wterm=wterm//SymmetrizeSlots[]//SymmetrizePattern[];
wterm=wterm/.Thread[workfree->freelist];
wterm=wterm/.Thread[workdummies->dummylist]
];

wexpr=standardterm/@wexpr;
termpatterns=List@@wexpr;
termpatterns=termpatterns/.a_ b_/;FreeQ[{a},Tensor[__]]->b;
If[Length[termpatterns]<1,Return[wexpr]];
termpatterns=standardpattern/@termpatterns;
termpatterns=Union[termpatterns/.Null->Sequence[],SameTest->(MatchQ[#1/.dum[i_]->k,#2/.dum[i_]->k]&)];
termpatterns=termpatterns/.dum[i_]:>With[{x=i},
Pattern[x,Blank[]]];
termpatterns=k_. termpatterns;
(* These are the standard dummy term patterns *)
(* In the following expression we SimplifyTensorSum only on patterns that generate more than one term. *)
wexpr=Fold[MapLevelPatterns[Simplify[If[Head[#]===Plus,hit=True;SimplifyTensorSum[#],#]]&,{{#2}}][#1]&,wexpr,termpatterns]//SymmetrizeSlots[]//SymmetrizePattern[];
On[RawIndex::notindex];
(* Handle simple sums of unrelated terms *)
If[hit==False,wexpr/.sum:HoldPattern[Plus[__]]:>SimplifyTensorSum[sum],wexpr]
]


SyntaxInformation[SimplifyTensorSum]={"ArgumentsPattern"->{_}};
SimplifyTensorSum[sum_]/;MemberQ[(Times|Plus),Head[sum]]:=
Module[{wsum,termindices,dummies,containsbadterms,i,termdummies,rule},
wsum=Expand[sum];
wsum=If[Head[wsum]===Plus,List@@wsum,{wsum}];
termindices=ParseTermIndices/@wsum;
containsbadterms=False;
Do[If[termindices[[i,3]]=!={},containsbadterms=True;Message[SimplifyTensorSum::badterm,wsum[[i]]]],{i,1,Length[wsum]}];
If[containsbadterms,Abort[]];
If[\[Not](SameQ@@Table[Sort/@termindices[[i,2]],{i,1,Length[wsum]}]),Message[SimplifyTensorSum::free];Abort[]];
dummies=UnsortedUnion[Join@@Table[termindices[[i,1]],{i,1,Length[wsum]}]];
Do[termdummies=termindices[[i,1]];
rule=Thread[termdummies->Take[dummies,Length[termdummies]]];
wsum[[i]]=wsum[[i]]/.rule,{i,1,Length[wsum]}];
Plus@@wsum
]


SimplifyTensorSum[expr_?(FreeQ[#,Tensor]&)]:=expr


SyntaxInformation[PatternReplaceIndex]={"ArgumentsPattern"->{{__},_,_.}};
PatternReplaceIndex[newindices:{_,___},patt_,checkdummies_:True][expr_Plus]:=PatternReplaceIndex[newindices,patt,checkdummies]/@expr

PatternReplaceIndex[newindices:{_,___},patt_,checkdummies_:True][expr_]:=
Module[{workpatt,workexpr,newflavors,patternindices,flavor,newworkindices,targetexpression,p,t,prules,patternindices2,targetindices,tindices,hit},

workpatt=patt/.Pattern->p;
newworkindices=Sort[newindices,OrderedQ[{RawIndex[#1],RawIndex[#2]}]&];
newflavors=GetIndexFlavor/@newworkindices;
patternindices=Cases[workpatt,p[i_,Blank[]],\[Infinity]]//Union;
patternindices2=patternindices/.{flavor[p[i_],_]->flavor[i],p[i_,_]->i};

If[Length[patternindices]!=Length[newindices],Message[PatternReplaceIndex::numindices,patt];Abort[]];

prules=Thread[patternindices->newworkindices];
targetexpression=workpatt/.prules;
targetindices=Flatten[Take[ParseTermIndices[targetexpression],2]];

If[checkdummies\[And]Sort[First[ParseTermIndices[targetexpression]]]=!=Sort[newindices],Message[PatternReplaceIndex::dummies,patt];Abort[]];
 
hit=False;workexpr=expr/.Pattern[Evaluate[t],restpattern_. patt]:>
Module[{commonindices,targindices},
tindices=Flatten[Take[ParseTermIndices[t/restpattern],2]];
commonindices=Intersection[tindices,targetindices];
tindices=Complement[tindices,commonindices ];
targindices=Complement[targetindices,commonindices ];
If[(GetIndexFlavor/@tindices)===(GetIndexFlavor/@targindices),hit=True;restpattern targetexpression,t]
];
If[checkdummies\[Or]\[Not]hit,workexpr,workexpr//IndexChange[Transpose[{tindices,newworkindices}]]]
]


SyntaxInformation[PermuteTensorSlots]={"ArgumentsPattern"->{_,_.}};
PermuteTensorSlots[label_Symbol,permutation_List][expr_]:=
Module[{order=Length[permutation]},
Which[\[Not](VectorQ[permutation,0<#<=order&]\[And]MatchQ[Signature[permutation],1|-1]),Message[PermuteTensorSlots::permutation,permutation];expr,
True,expr/.Tensor[label,ups_/;Length[ups]==order,downs_]:>Tensor[label,Part[ups,permutation],Part[downs,permutation]]]
]


PermuteTensorSlots[label_Symbol][expr_]:=
expr/.t:Tensor[label,_,_]:>
Module[{slots},
slots=Reverse/@ExtractTensorSlots[t];
SlotsToTensor[Reverse/@Sort[slots,First[#1]<=First[#2]&]]
]


SyntaxInformation[ExtractTensorSlots]={"ArgumentsPattern"->{_}};
ExtractTensorSlots[Tensor[label_,ups_,downs_]]:=
Transpose[{ups,downs}]/.{{index_,Void}->{label,index,-1},{Void,index_}->{label,index,1}}


SyntaxInformation[SlotsToTensor]={"ArgumentsPattern"->{_}};
SlotsToTensor[slots:{{label_Symbol,_,1|-1}..}]:=
Module[{work=slots,ups,downs},
{ups,downs}=Transpose[work/.{{_,index_,-1}->{index,Void},{_,index_,1}->{Void,index}}];
Tensor[label,ups,downs]
]


SyntaxInformation[ExtractTermSlots]={"ArgumentsPattern"->{_}};
ExtractTermSlots[term_]:=
Module[
{factor=1,work,f},
If[FreeQ[term,Tensor[_,_,_]],Return[{1,{}}]];
Attributes[f]=Flat;
work=If[Head[term]===Times,f@@term,f[term]];
(* Convert the term to a product of tensors and factors *)
work=work/.a_Function:>If[Length[a]<3,Last[a],Part[a,2]];
If[MatchQ[IndexParsingRules, (Rule|RuleDelayed)[_,_]|{ (Rule|RuleDelayed)[_,_]..}],
work=work/.IndexParsingRules];
work=work/.
(TotalD|AbsoluteD|LieD|TensorForms1`TensorialForms`ExteriorD)[t_,___]->f[t];
work=work
//.HoldPattern[PartialD[t_,dvars_]]:>f[t, Tensor[Unique[Global`tlab],Table[Void,{Length[Flatten[{dvars}]]}],Flatten[{dvars}]]];
work=work
//.HoldPattern[CovariantD[t_,dvars_]]:>f[t, Tensor[Unique[Global`tlab],Table[Void,{Length[Flatten[{dvars}]]}],Flatten[{dvars}]]];
work=work/.HoldPattern[PartialD[_][t_,dvars_]]:>f[t,f@@Cases[dvars,Tensor[l_,ups_,downs_]->Tensor[l,downs,ups],{0,1}]];
work=work/.
Tensor[t_]:>If[FreeQ[{t},Plus],f[t] ,scalar];
work=work/.t_Tensor[___]->f[t];
work=work/.
(Dot|CircleTimes|TensorForms1`TensorialForms`Wedge)->f/.Tensor[_]->1;

(* Extract nontensor factor and tensor factors *)
factor=Times@@Select[work,Head[#]=!=Tensor&];
work=Cases[work,Tensor[_,_,_]];

{factor,ExtractTensorSlots/@work}/.f->List
]


SyntaxInformation[CanonicalUpDowns]={"ArgumentsPattern"->{_}};
CanonicalUpDowns[term_]/;MatchQ[Head[term],Tensor|Times]\[And]FreeQ[{term},Plus]:=
Module[{dummies,slots},
dummies=First[ParseTermIndices[term]];
slots=Flatten[Last@ExtractTermSlots[term],1];
Fold[If[\[Not]OrderedQ[Cases[slots,{_,#2,sign_}->sign]],UpDownSwap[#2][#1],#1]&,term,dummies]
]


SyntaxInformation[UpDownAdjust]={"ArgumentsPattern"->{_}};
UpDownAdjust[sum_Plus]:=
Module[
{terms=List@@sum,
tagID=$$TNUM,
dummies,sumslots,nterms,termgroups},
nterms=Length[terms];
dummies=First[ParseTermIndices[#]]&/@terms;

(* Generate the List of term slots, each sorted and tagged with term number *)
sumslots=Sort[Flatten[Rest[ExtractTermSlots[#]],2]]&/@terms;
sumslots= MapThread[Join[#1,{{tagID,#2,-1}}]&,{sumslots,Range[nterms]}];

(* Drop up/down number, sort slots and split to terms with similar structures *)
workslots=Sort@Map[Drop[#,-1]&,sumslots,{2}];
workslots=Split[workslots,Drop[#1,-1]==Drop[#2,-1]&];

(* Select cases that have multiple terms and dummy indices *)
workslots =Select[workslots,(Length[#]>1)\[And]
Length[Part[dummies,Part[#,1,-1,2]]]>0&];

Do[termgroups=Cases[Part[workslots,i],{__,{tagID,n_}}->n];
terms=MapAt[CanonicalUpDowns,terms,Partition[termgroups,1]],
{i,1,Length[workslots]}];
Plus@@terms
]


SyntaxInformation[KroneckerEvaluate]={"ArgumentsPattern"->{_}};
KroneckerEvaluate[\[Delta]_][expr_]:=
Module[{basetest},
basetest[indices_List]:=Module[{windices=indices/.Void->Sequence[]},
And@@(BaseIndexQ/@windices)\[And]SameQ@@(GetIndexFlavor/@windices)];
expr/.ten:Tensor[\[Delta],up_?basetest,down_?basetest]:>
Catch[Module[{ups=up/.Void->Sequence[],downs=down/.Void->Sequence[]},
If[Length[ups]!=Length[downs],Throw[ten]];
If[\[Not]Union[ups,downs]===Sort[ups],Throw[0]];
Signature[ups]Signature[downs]
]]
]


kSubsets[l_List,0] := { {} }
kSubsets[l_List,1] := Partition[l,1]
kSubsets[l_List,k_Integer?Positive] := {l} /; (k == Length[l])
kSubsets[l_List,k_Integer?Positive] := {}  /; (k > Length[l])
kSubsets[l_List,k_Integer?Positive] :=
	Join[
		Map[(Prepend[#,First[l]])&,kSubsets[Rest[l],k-1]],
		kSubsets[Rest[l],k]
	]


SyntaxInformation[KroneckerContract]={"ArgumentsPattern"->{_}};
KroneckerContract[\[Delta]_][expr_]:=
(expr//KroneckerAbsorb[\[Delta]])/.tensor:Tensor[\[Delta],tup_,tdown_]:>
Module[{r,t,n,nup,indices,up,down,sign,voids},
n=NDim;
indices=ParseTermIndices[tensor];
dummies=indices[[1]];
t=Length[dummies];
{up,down}=indices[[2]];
nup=Length[up];
If[nup!=Length[down],Message[KroneckerContract::indices,tensor];Abort[]];
r=t+nup;
voids=Array[Void&,nup];
sign=Signature[If[MemberQ[dummies, #],#,Unevaluated[Sequence[]]]&/@tup]/Signature[If[MemberQ[dummies, #],#,Unevaluated[Sequence[]]]&/@tdown];
sign *
Which[
t==0,tensor,
nup>0,(n-r+t)!/(n-r)!  Tensor[\[Delta],{Sequence@@up,Sequence@@voids},{Sequence@@voids,Sequence@@down}],
True,(n-r+t)!/(n-r)! ]
]


SyntaxInformation[FullKroneckerExpand]={"ArgumentsPattern"->{_}};
FullKroneckerExpand[\[Delta]_][expr_]:=
(expr//KroneckerContract[\[Delta]])/.tensor:Tensor[\[Delta],_,_]:>
Module[{up,down},
{up,down}=ParseTermIndices[tensor][[2]];
If[Length[up]!=Length[down],Message[FullKroneckerExpand::indices,tensor];Abort[]];
Det[Outer[Tensor[\[Delta],{#1,Void},{Void,#2}]&,up,down]]
]


SyntaxInformation[PartialKroneckerExpand]={"ArgumentsPattern"->{_,_,_,_.}};
PartialKroneckerExpand[\[Delta]_Symbol,order_Integer?Positive,suborder_Integer?Positive,expandup_:True][expr_]:=
expr/.tensor:Tensor[\[Delta],u_,_]/;Length[u]==2 order\[And]Length[u]>2suborder:>
Module[{up,down,up1,up2,down1,down2,signs,voids1,voids2},
{up,down}=ParseTermIndices[tensor][[2]];
If[Length[up]!=Length[down],Message[PartialKroneckerExpand::indices,tensor];Abort[]];

If[expandup=!=False,
up1=Take[up,suborder];
up2=Drop[up,suborder];
down1=kSubsets[down,suborder];
down2=Complement[down,#]&/@down1;
signs=Signature[#]/Signature[down]&/@MapThread[Join[#1,#2]&,{down1,down2}],

down1=Take[down,suborder];
down2=Drop[down,suborder];
up1=kSubsets[up,suborder];
up2=Complement[up,#]&/@up1;
signs=Signature[#]/Signature[up]&/@MapThread[Join[#1,#2]&,{up1,up2}]
];
voids1=Array[Void&,suborder];
voids2=Array[Void&,order-suborder];
If[expandup,
Plus@@MapThread[#1 Tensor[\[Delta],Join[up1,voids1],Join[voids1,#2]]Tensor[\[Delta],Join[up2,voids2],Join[voids2,#3]]&,{signs,down1,down2}],
Plus@@MapThread[#1 Tensor[\[Delta],Join[#2,voids1],Join[voids1,down1]]Tensor[\[Delta],Join[#3,voids2],Join[voids2,down2]]&,{signs,up1,up2}]]
]


KAUpTest[i_,termexpr_]:=MemberQ[Part[ParseTermIndices[termexpr],2,1], i]


KADownTest[i_,termexpr_]:=MemberQ[Part[ParseTermIndices[termexpr],2,2], i]


GenNewKATerm[i_,j_][term_]:=
Module[{uq=Unique[q],u1,newterm},
u1=If[IndexFlavorQ[Head[i]],Head[i][uq],uq];
newterm=term//IndexChange[{i,u1}];
newterm/.u1->j
]


SyntaxInformation[KroneckerAbsorb]={"ArgumentsPattern"->{_}};
KroneckerAbsorb[\[Delta]_][expr_]:=
expr//.{Tensor[\[Delta],{i_,Void},{Void,j_}]term_/;KADownTest[i,term]:> GenNewKATerm[i,j][term],
Tensor[\[Delta],{j_,Void},{Void,i_}]term_/;KAUpTest[i,term]:> GenNewKATerm[i,j][term],

Tensor[\[Delta],{Void,i_},{j_,Void}]term_/;KADownTest[i,term]:>GenNewKATerm[i,j][term],
Tensor[\[Delta],{Void,j_},{i_,Void}]term_/;KAUpTest[i,term]:>GenNewKATerm[i,j][term]}


SyntaxInformation[PermutationPseudotensor]={"ArgumentsPattern"->{_}};
PermutationPseudotensor[n_]:=
Module[
{indxs=Table[Unique[q],{n}],iters},
iters=MapThread[{#1,1,n}&,{indxs}];
Table[Signature[indxs],Evaluate[Sequence@@iters]]
]


SyntaxInformation[PermutationSymbolRule]={"ArgumentsPattern"->{_}};
PermutationSymbolRule[e_]:=
Tensor[e,ups_List,downs_List]/;
Module[{},
Which[
Length[ups]!=NDim,False,
Length[downs]!=NDim,False,
\[Not]SameQ@@(Head/@ups),False,
\[Not]SameQ@@(Head/@downs),False,
\[Not](And@@(#===Void&/@ups))\[And](And@@(#=!=Void&/@downs)),False,
\[Not](And@@(#===Void&/@downs))\[And](And@@(#=!=Void&/@ups)),False,
First[ups]===Void\[And]\[Not](And@@(BaseIndexQ/@downs)),False,
First[downs]===Void\[And]\[Not](And@@(BaseIndexQ/@ups)),False,
True,True]
]:>
If[
First[ups]===Void,Signature[GetBaseIndices[First@downs]]Signature[downs],Signature[GetBaseIndices[First@ups]]Signature[ups]]


(* ::Input:: *)
SyntaxInformation[UseCoordinates]={"ArgumentsPattern"->{_.,_.,_.}};
UseCoordinates[namelist_List,x_:Global`x,flavor_:Identity][expr_]:=
Module[{bases,i},
bases=GetBaseIndices[flavor@i];
If[Length[namelist]!=Length[bases],Return[expr]];
expr/.Thread[Table[Tensor[x,{flavor@bases[[i]]},{Void}],{i,1,Length[bases]}]->namelist]
]


UseCoordinates[x_:Global`x,flavor_:Identity][expr_]:=
Module[{bases,i},
bases=GetBaseIndices[flavor@i];
If[Length[bases]>0\[And]And@@(Head[#]===Symbol&/@bases),UseCoordinates[bases,x,flavor][expr],expr]]


SyntaxInformation[CoordinatesToTensors]={"ArgumentsPattern"->{_.,_.,_.}};
CoordinatesToTensors[coordinates_List,xlab_:Global`x,flavor_:Identity][expr_]:=
Module[{bases,i},
bases=GetBaseIndices[flavor@i];
expr/.Thread[coordinates->Table[Tensor[xlab,{flavor@Part[bases,i]},{Void}],{i,1,Length[bases]}]]
]


CoordinatesToTensors[xlab_:Global`x,flavor_:Identity][expr_]:=
Module[{bases,i},
bases=GetBaseIndices[flavor@i];
If[Length[bases]>0\[And]And@@(Head[#]===Symbol&/@bases),CoordinatesToTensors[bases,xlab,flavor][expr],expr]
]


SyntaxInformation[SymmetrizeSlots]={"ArgumentsPattern"->{___}};
SymmetrizeSlots[][expr_]:=SymmetrizeSlots[Automatic][expr];


SymmetrizeSlots[sargs__][expr_]:=
Module[{plabel,porder,psymmetry,passedsymmetry=False},

If[sargs=!=Automatic\[And]Length[{sargs}]==3,{plabel,porder,psymmetry}={sargs};passedsymmetry=True];
passedsymmetry=If[passedsymmetry\[And]Head[plabel]===Symbol\[And]Head[porder]===Integer\[And]porder>0,True,False];

expr/.tensor:Tensor[label_,ups_,downs_]:>
Catch[Module[
{order=Length[ups],
dummies=First@ParseTermIndices[tensor],
tsign=1,
symmetry,slots,processsymmetry,duplicatedummies},

duplicatedummies[sslots_]:=
Module[{work},
(* Rows over the dummy indices, columns over symmetry groups *)
work=Outer[
Module[{indices},
indices=Cases[#2,{_Symbol,index_,1|-1}->index,\[Infinity]];
MatchQ[#1,Alternatives@@indices]
]&,
dummies,sslots,1];
(* Does each dummy occur in more than one group? *)
work=(Count[#,True,\[Infinity]]>1&)/@work;
(* Do any of the dummies occur in more than one group? *)
Or@@work
];

processsymmetry[subsymmetry_]:=
Module[
{symtype=Head[subsymmetry],
symslots,subslots,neworder,newsubslots},

If[symtype===List,Return[subsymmetry]];

(* Sort integer arguments and convert symmetries to partitioned lists *)
symslots=subsymmetry/.
{args:_Integer..}:>Sort[{args}]/.
(Symmetric|AntiSymmetric)[args:_List..]->{args}/.(Symmetric|AntiSymmetric)[args:_Integer..]:>Partition[Sort[{args}],1];
(* Extract the subslots for this symmetry and obtain the new order *)
subslots=Part[slots,#]&/@symslots;
neworder=Ordering[subslots];
tsign=Which[
symtype===AntiSymmetric\[And](duplicatedummies[subslots]\[Or]Length[Union[subslots]]<Length[subslots]),0,
symtype===AntiSymmetric,tsign Signature[neworder]Signature[symslots],
True,tsign];
(* The subslots put into canonical order *)
newsubslots=Flatten[Part[subslots,neworder],1];
(* Replace the subslots in the overall slots *)
slots=ReplacePart[slots,newsubslots,Partition[Flatten[symslots,1],1],Partition[Range[Length[newsubslots]],1]];
(* Convert the subsymmetry to a nonsymmetrical group for higher level symmetries *)
List@@subsymmetry
];

If[
passedsymmetry,
symmetry=psymmetry; If[label=!=plabel\[Or]order=!=porder,Throw[tensor]],
symmetry=TensorSymmetry[label,order];
If[Head[symmetry]===TensorSymmetry,Throw[tensor]]
];

slots=ExtractTensorSlots[tensor];
Map[processsymmetry,symmetry,{0,-2}];
tsign SlotsToTensor[slots]
]]
]


SyntaxInformation[SymmetrizePattern]={"ArgumentsPattern"->{_.,_.}};
SymmetrizePattern[][expr_]:=
Fold[SymmetrizePattern[Sequence@@#2][#1]&,expr,PatternSymmetries]


SymmetrizePattern[pattern_,insymmetries:{{-1|0|1,{_?SymbolicIndexQ,__?SymbolicIndexQ}|{{_?SymbolicIndexQ,__?SymbolicIndexQ},{_?SymbolicIndexQ,__?SymbolicIndexQ}..}}..}][expr_]:=Module[{symmetries},
symmetries=insymmetries/.{i_Integer,sym_List}:>{i,Sort[sym]};
SymmetrizePattern2[pattern,symmetries][expr]]


SymmetrizePattern2[pattern_,symmetries_][expr_]:=
Module[{i,symlength=Length[symmetries]},
expr/.(term:h_. pattern):>
Module[{wterm=term/h,fromindices,toindices,sign},
Do[
fromindices=Part[symmetries,i,2];
toindices=Sort[Part[symmetries,i,2]];
sign=Switch[Part[symmetries,i,1],
0,0,
1,1,
-1,Signature[fromindices]Signature[toindices]];
wterm=sign wterm/.Thread[Flatten[fromindices]->Flatten[toindices]],
{i,1,symlength}];
h wterm]
]


SyntaxInformation[DeclarePatternSymmetries]={"ArgumentsPattern"->{__}};
DeclarePatternSymmetries[pattern_,symmetries:{{-1|0|1,{_?SymbolicIndexQ,__?SymbolicIndexQ}|{{_?SymbolicIndexQ,__?SymbolicIndexQ},{_?SymbolicIndexQ,__?SymbolicIndexQ}..}}..}]:=(PatternSymmetries=Union[Join[{{pattern,symmetries}},PatternSymmetries]];)


DeclarePatternSymmetries[args:{_,{{-1|0|1,{_?SymbolicIndexQ,__?SymbolicIndexQ}|{{_?SymbolicIndexQ,__?SymbolicIndexQ},{_?SymbolicIndexQ,__?SymbolicIndexQ}..}}..}}..]:=
(DeclarePatternSymmetries@@@{args};)


SyntaxInformation[Symmetric]={"ArgumentsPattern"->{__}};
Symmetric[args__List/;Length[{args}]>1,weighting_:True][term_]:=Fold[Symmetric[#2,weighting][#1]&,term,{args}]


Symmetric[ind_,weighting_:True][term_]:=
Module[{indperm,tens,upindices,downindices,numindices=Length[ind],work=Expand[term],kk},

Switch[Head[work],
List,Symmetric[ind,weighting]/@work,
Equal|Unequal|Less|Greater|LessEqual|GreaterEqual,Symmetric[ind]/@work,
Plus,Symmetric[ind,weighting]/@work,
_,
{upindices,downindices}=Part[ParseTermIndices[work],2];
If[Count[ind,Alternatives@@Flatten[{upindices,downindices}]]==0,Return[work]];
If[\[Not](Count[ind,Alternatives@@upindices]==numindices\[Or]Count[ind,Alternatives@@downindices]==numindices),
Message[Symmetric::indices,ind,upindices,downindices];Abort[]];
indperm=Permutations[ind];
tens=Table[work//IndexChange[Transpose[{ind,Part[indperm,kk]}]],{kk,1,Length[indperm]}];
Plus@@tens/If[weighting,Length[indperm],1]]
]


SyntaxInformation[AntiSymmetric]={"ArgumentsPattern"->{__}};
AntiSymmetric[args__List/;Length[{args}]>1,weighting_:True][term_]:=Fold[AntiSymmetric[#2,weighting][#1]&,term,{args}]


AntiSymmetric[ind_List,weighting_:True][term_]:=
Module[{indperm,signs,tens,upindices,downindices,numindices=Length[ind],work=Expand[term],kk},

Switch[Head[work],
List,AntiSymmetric[ind,weighting]/@work,
Equal|Unequal|Less|Greater|LessEqual|GreaterEqual,AntiSymmetric[ind]/@work,
Plus,AntiSymmetric[ind,weighting]/@work,
_,
{upindices,downindices}=Part[ParseTermIndices[term],2];
If[\[Not](Count[ind,Alternatives@@upindices]==numindices\[Or]Count[ind,Alternatives@@downindices]==numindices),
Message[AntiSymmetric::indices,ind,upindices,downindices];Abort[]];
indperm=Permutations[ind];
signs=(Signature[##1]&)/@indperm;tens=Table[work//IndexChange[Transpose[{ind,Part[indperm,kk]}]],{kk,1,Length[indperm]}];
(Signature[ind] signs.tens)/If[weighting,Length[indperm],1]]]


SyntaxInformation[udsymQ]={"ArgumentsPattern"->{_}};
udsymQ[udsym_Symbol]:=And@@(#=="u"\[Or]#=="d"&/@Characters@SymbolName[udsym]);


SyntaxInformation[Parseud]={"ArgumentsPattern"->{_}};
Parseud[udsym_[args__]]:=
Module[
{symcharacters=Characters@SymbolName[udsym],
numslots,ups,downs,i},
numslots=Length[symcharacters];
If[numslots!=Length[{args}],Message[Parseud::Arguments,udsym[args]];Abort[]];
If[And@@(#=="u"\[Or]#=="d"&/@symcharacters)==False,Message[Parseud::BadHead,udsym];Abort[]];
ups=downs=Table[Void,{numslots}];
(* Insert indices into ups and downs list *)
Do[If[Part[symcharacters,i]=="u",
ups=ReplacePart[ups,i->Part[{args},i]],
downs=ReplacePart[downs,i->Part[{args},i]]],{i,1,numslots}];
Sequence@@{ups,downs}
]


SyntaxInformation[DefineTensor]={"ArgumentsPattern"->{__}};
DefineTensor[t__]:=
Module[{labels=Flatten[{t}],f},
f=Function[label,(label[i_[args__]]/;TrueQ[udsymQ[i]]:=Tensor[label,i[args]//Parseud];
DefinedTensors=Union[DefinedTensors,{label}];)];
f/@labels;]


SyntaxInformation[ClearTensor]={"ArgumentsPattern"->{__}};
ClearTensor[t__]:=
Module[{labels=Flatten[{t}],f},
f=Function[label,(label[i_[args__]]/;TrueQ[udsymQ[i]]=.;
DefinedTensors=Complement[DefinedTensors,{label}];)];
f/@labels;]


SyntaxInformation[TensorValueRules]={"ArgumentsPattern"->{__}};
TensorValueRules[labels__]/;Length[{labels}]>1:=Fold[Join,{},If[Head[TensorValueRules[#]]===TensorValueRules,{},TensorValueRules[#]]&/@{labels}]


Attributes[SetTensorValues]={HoldFirst};

SyntaxInformation[SetTensorValues]={"ArgumentsPattern"->{_,_,_.}};
SetTensorValues[tensor_,value_]/;MatchQ[Hold[tensor],Hold[Tensor[_]]]:=
Module[{label},
ClearTensorValues[tensor];
label=Part[tensor,1];
With[{form=Tensor[label],val=value},
Evaluate[label]/:form=val];
]


SetTensorValues[intensor_,values_List,permissive_:False]:=
Module[
{tensor=intensor,label,indices,windices,iterators,valdimensions=Dimensions[values], indexstructure,numindices,i,index,indexdim,indexbase,indexbases,indexflavor,indexflavors,indexdimensions,indexchanges},

indices=Sort[Flatten[Part[ParseTermIndices[tensor],{1,2}]],OrderedQ[{RawIndex[#1],RawIndex[#2]}]&];
numindices=Length[indices];

If[Length[indices]>Length[valdimensions],Message[SetTensorValueRules::dim];Return[$Failed]];

indexstructure=
Table[
index=Part[indices,i];
indexflavor=GetIndexFlavor[index];
indexbase=GetBaseIndices[index];
indexdim=Length[indexbase];
{index,indexflavor,indexbase,indexdim},{i,1,numindices}];

indexdimensions=Table[Part[indexstructure,i,4],{i,1,numindices}];
indexflavors=Table[Part[indexstructure,i,2],{i,1,numindices}];
indexbases=Table[Part[indexstructure,i,3],{i,1,numindices}];

If[Take[valdimensions,numindices]=!=indexdimensions,Message[SetTensorValues::size];Return[$Failed]];

If[\[Not]permissive\[And]Length[valdimensions]>numindices\[And]\[Not]SameQ@@Join[{Last[indexdimensions]},Drop[valdimensions,numindices]],Message[SetTensorValues::size];Return[$Failed]];

ClearTensorValues[tensor];

windices=Unique/@RawIndex/@indices;

iterators=MapThread[{#,1,#2}&,{windices,indexdimensions}];
label=First[tensor];
indexchanges:=Table[{Part[indices,i],Part[indexflavors,i]@Part[indexbases,i][[Part[windices,i]]]},{i,1,numindices}];

Do[
With[
{form=tensor//IndexChange[indexchanges],val=Part[values,Sequence@@windices]},
If[form=!=val,Evaluate[label]/:form=val]],
Evaluate[Sequence@@iterators]]
]


Attributes[SetTensorValueRules]={HoldFirst};


SyntaxInformation[SetTensorValueRules]={"ArgumentsPattern"->{_,_,_.}};
SetTensorValueRules[tensor_,value_]/;MatchQ[Hold[tensor],Hold[Tensor[_]]]:=
Module[{label},
ClearTensorValues[tensor];
label=Part[tensor,1];
TensorValueRules[label]=
Switch[Head[TensorValueRules[label]],
List,Join[TensorValueRules[label],{Tensor[label]->value}],
_,{Tensor[label]->value}];
]


SetTensorValueRules[intensor_,values_List,permissive_:False]:=
Module[
{tensor=intensor,label,indices,windices,iterators,val,newrules,valdimensions=Dimensions[values], indexstructure,numindices,i,index,indexdim,indexbase,indexbases,indexflavor,indexflavors,indexdimensions,indexchanges},

indices=Sort[Flatten[Part[ParseTermIndices[tensor],{1,2}]],OrderedQ[{RawIndex[#1],RawIndex[#2]}]&];
numindices=Length[indices];

If[Length[indices]>Length[valdimensions],Message[SetTensorValueRules::dim];Return[$Failed]];

indexstructure=
Table[
index=Part[indices,i];
indexflavor=GetIndexFlavor[index];
indexbase=GetBaseIndices[index];
indexdim=Length[indexbase];
{index,indexflavor,indexbase,indexdim},{i,1,numindices}];

indexdimensions=Table[Part[indexstructure,i,4],{i,1,numindices}];
indexflavors=Table[Part[indexstructure,i,2],{i,1,numindices}];
indexbases=Table[Part[indexstructure,i,3],{i,1,numindices}];

If[Take[valdimensions,numindices]=!=indexdimensions,Message[SetTensorValueRules::size];Return[$Failed]];

If[\[Not]permissive\[And]Length[valdimensions]>numindices\[And]\[Not]SameQ@@Join[{Last[indexdimensions]},Drop[valdimensions,numindices]],Message[SetTensorValueRules::size];Return[$Failed]];

ClearTensorValues[tensor];

windices=Unique/@RawIndex/@indices;

iterators=MapThread[{#,1,#2}&,{windices,indexdimensions}];
label=First[tensor];
indexchanges:=Table[{Part[indices,i],Part[indexflavors,i]@Part[indexbases,i][[Part[windices,i]]]},{i,1,numindices}];

newrules=
Table[
val=Part[values,Sequence@@windices];
With[{form=tensor//IndexChange[indexchanges]},
form->val],
Evaluate[Sequence@@iterators]]//Flatten;
newrules=Select[newrules,First[#]=!=Last[#]&];

TensorValueRules[label]=
Switch[Head[TensorValueRules[label]],
List,Join[TensorValueRules[label],newrules],
_,newrules];
]


SyntaxInformation[ClearTensorValues]={"ArgumentsPattern"->{_}};
Attributes[ClearTensorValues]={HoldFirst};
ClearTensorValues[tensorlist_]/;MatchQ[Hold[tensorlist],Hold[List[__]]]:=
(Map[ClearTensorValues,Hold[tensorlist],{2}]//ReleaseHold;)


ClearTensorValues[intensor_]:=
Module[
{tensor,label,p,form,upindices,downindices,upflavors,downflavors},

Switch[Hold[intensor],
Hold[Tensor[_]],
label=Part[Hold[intensor],1,1];form=HoldPattern[Tensor[p]]/.p->label,
_,
tensor=intensor;
label=Part[tensor,1];
upindices=Part[tensor,2];
downindices=Part[tensor,3];
upflavors=GetIndexFlavor/@upindices;
downflavors=GetIndexFlavor/@downindices;
form=
Tensor[label,
ups:Map[If[#===Void,Void,_]&,upindices],downs:Map[If[#===Void,Void,_]&,downindices]]/;(upflavors===GetIndexFlavor/@ups)\[And](downflavors===GetIndexFlavor/@downs)
];

With[{wform=form,wlabel=label},
UpValues[wlabel]=Select[UpValues[wlabel],FreeQ[#,wform]&];
TensorValueRules[wlabel]=If[Head[TensorValueRules[wlabel]]===TensorValueRules,{},Select[TensorValueRules[wlabel],FreeQ[First[#],wform]&]]];
]


SyntaxInformation[SelectedTensorRules]={"ArgumentsPattern"->{_}};
SelectedTensorRules[pattern_]:=
Module[{labels,work},
labels=Union@Cases[pattern,Tensor[label_,___]->label,{0,\[Infinity]}];
work =Cases[TensorValueRules@@labels,HoldPattern[Rule[_,rhs_/;rhs=!=0]]];
Select[work,MatchQ[First[#],pattern]&]
]


SyntaxInformation[DeclareZeroTensor]={"ArgumentsPattern"->{_}};
DeclareZeroTensor[lab_]:=
Module[{},
lab/:Tensor[lab,{_?(FreeQ[#,Pattern|Blank]\[And](#===Void\[Or]BaseIndexQ[#])&)..},{_?(FreeQ[#,Pattern|Blank]\[And](#===Void\[Or]BaseIndexQ[#])&)..}]:=0;
Tensor/:(z:Tensor[lab,_,_])fac_:=z;
Tensor/:(z:Tensor[lab,_,_])+term_:=term;
]


SyntaxInformation[MetricSimplify]={"ArgumentsPattern"->{_,_.}};
MetricSimplify[g_,dopartials_:False][inexpr_]:=
Module[{expr=Distribute[inexpr,Plus,Times]},
Which[
Head[expr]===List,MetricSimplify[g,dopartials]/@expr,
MemberQ[{Equal,Unequal,Less,Greater,LessEqual,GreaterEqual},Head[expr]],MetricSimplify[g,dopartials][Distribute[#,Plus,Times]]&/@expr,
Head[expr]===Plus,MetricSimplify[g,dopartials]/@expr,
True,MetricSimplify2[g,dopartials][Distribute[expr,Plus,Times]]]
]


MetricSimplify2[g_,dopartials_][expr_]:=
Module[{wexpr=expr,gmatch,routine,tlab,t2},

(* gmatch determines if there is an index raising or lowering match between a metric tensor m and a tensor term t. It sets the proper routine for changing the index in t and returns True if there is a match, but otherwise returns False. *)
gmatch[m_,t_]:=Module[{dummy,newindex,gtdummies=Complement[Part[ParseTermIndices[m t],1],Part[ParseTermIndices[t],1]],gups,gdowns,gindices},

If[Length[gtdummies]==0,Return[False]];
{gups,gdowns}=List@@Part[m,{2,3}]/.Void->Sequence[];
gindices=Union[gups,gdowns];
If[Length[gindices]<2,Return[False]];
If[(Intersection[gindices,gtdummies]==={})\[Or]\[Not]SameQ@@((Head/@gindices)/.Integer->Symbol),Return[False]];
dummy=First@Sort[gtdummies];
newindex=First@Complement[gindices,{dummy}];
routine=
Which[
Length[gups]==1,ReplaceIndex[dummy,newindex],MemberQ[Part[ParseTermIndices[t],2,1],dummy],LowerIndex[dummy,newindex],
True,RaiseIndex[dummy,newindex]];
True];

wexpr=wexpr//.
{f_. (m:Tensor[g,_,_]) (t:Tensor[_,_,_])/;gmatch[m,t]:>f routine[t],

f_. (m:Tensor[g,_,_]) HoldPattern[CovariantD[t:Tensor[_,_,_],upindices_,downindices_]]/;gmatch[m,t]:>f CovariantD[routine[t],upindices,downindices],

f_. (m:Tensor[g,_,_]) HoldPattern[CovariantD[t_,upindices_,downindices_]]/;gmatch[m,t2=Tensor[tlab,upindices,downindices]]:>f CovariantD[t,Sequence@@Part[routine[t2],{2,3}]],

f_. (m:Tensor[g,_,_]) HoldPattern[AbsoluteD[t:Tensor[_,_,_],difvars_]]/;gmatch[m,t]:>f AbsoluteD[routine[t],difvars]};

If[dopartials,wexpr=wexpr//.{f_. (m:Tensor[g,_,_]) HoldPattern[PartialD[t:Tensor[_,_,_],indices_]]/;gmatch[m,t]:>f PartialD[routine[t],indices],f_. (m:Tensor[g,_,_]) HoldPattern[PartialD[labs:{_,_,_,_}][t:Tensor[_,_,_],coords_]]/;gmatch[m,t]:>f PartialD[labs][routine[t],coords],f_. (m:Tensor[g,_,_]) HoldPattern[TotalD[t:Tensor[_,_,_],difvars_]]/;gmatch[m,t]:>f TotalD[routine[t],difvars]}];

wexpr=wexpr//KroneckerAbsorb[g];
wexpr=wexpr/.a:(Tensor[g,{i_?BaseIndexQ,Void},{Void,j_?BaseIndexQ}]|Tensor[g,{Void,j_?BaseIndexQ},{i_?BaseIndexQ,Void}]):>Which[Head[i]=!=Head[j],a,i===j,1,True,0];
wexpr/.{HoldPattern[CovariantD[Tensor[g,{a_Symbol,b_Symbol},{Void,Void}],{Void},{c_Symbol}]]/;\[Not](BaseIndexQ[a]||BaseIndexQ[b]||BaseIndexQ[c])->0,HoldPattern[CovariantD[Tensor[g,{Void,Void},{a_Symbol,b_Symbol}],{Void},{c_Symbol}]]/;\[Not](BaseIndexQ[a]||BaseIndexQ[b]||BaseIndexQ[c])->0,HoldPattern[CovariantD[Tensor[g,{a_Symbol,b_Symbol},{Void,Void}],{Void..},{_Symbol?(\[Not]BaseIndexQ[#]&)..}]]/;\[Not](BaseIndexQ[a]||BaseIndexQ[b])->0,HoldPattern[CovariantD[Tensor[g,{Void,Void},{a_Symbol,b_Symbol}],{Void..}{_Symbol?(\[Not]BaseIndexQ[#]&)..}]]/;\[Not](BaseIndexQ[a]||BaseIndexQ[b]||BaseIndexQ[c])->0}]


SyntaxInformation[CalculateChristoffels]={"ArgumentsPattern"->{_,_.,_.}};
CalculateChristoffels[labs:{x_Symbol,\[Delta]_Symbol,g_Symbol,_},flavor_:Identity,simplifyfunc_:Identity]/;flavor===Identity\[Or]IndexFlavorQ[flavor]:=
Module[
{a,b,c,work,downChristoffel,upChristoffel},

work=1/2(PartialD[g@Global`dd[c,a],b]+PartialD[g@Global`dd[a,b],c]-PartialD[g@Global`dd[b,c],a])//ToFlavor[flavor];
work=work//ExpandPartialD[labs];
work=work//ToArrayValues[]//MetricSimplify[\[Delta]];
downChristoffel=Map[simplifyfunc,work,{3}];
upChristoffel=Map[simplifyfunc,(g@Global`uu[a,b]//ToFlavor[flavor]//ToArrayValues[]).downChristoffel,{3}];
{downChristoffel,upChristoffel}
]


SyntaxInformation[CalculateRiemannd]={"ArgumentsPattern"->{_,_.,_.}};
CalculateRiemannd[labs_,flavor_:Identity,simplifyroutine_:Identity]:=
Module[
{Rdddd,selectindices,array,genconditions,a,b,c,d,e,term1,term2,bindices,i,x,\[Delta],g,\[CapitalGamma],\[CapitalGamma]up,\[CapitalGamma]down,xup,ndim,basis},
basis=GetBaseIndices[flavor@i];
ndim=Length[basis];

{x,\[Delta],g,\[CapitalGamma]}=labs;
\[CapitalGamma]up[a_,b_,c_]:=Tensor[\[CapitalGamma],{a,Void,Void},{Void,b,c}];
\[CapitalGamma]down[a_,b_,c_]:=Tensor[\[CapitalGamma],{Void,Void,Void},{a,b,c}];
xup[a_]:=Tensor[x,{a},{Void}];

array=Table[{a,b,c,d},{a,1,ndim},{b,1,ndim},{c,1,ndim},{d,1,ndim}];selectindices=
Cases[Flatten[array,3],{a_,b_,c_,d_}/;
a!=b\[And]c!=d
\[And]((a==c\[And]b==d\[And]a<b)
\[Or](a==c\[And]b<d)
\[Or](a<b<c<d)
\[Or](a<c<b<d))];
bindices[indices_List]:=(flavor[#1]&)/@basis[[indices]];

Do[
{a,b,c,d}=bindices[selectindices[[i]]];
term1=\[CapitalGamma]up[flavor@e,b,c]\[CapitalGamma]down[flavor@e,a,d]-\[CapitalGamma]up[flavor@e,b,d]\[CapitalGamma]down[flavor@e,a,c]+PartialD[labs][\[CapitalGamma]down[a,b,d],xup[c]]-PartialD[labs][\[CapitalGamma]down[a,b,c],xup[d]]//EinsteinSum[];
term1=term1//.TensorValueRules[\[CapitalGamma],g]//MetricSimplify[\[Delta]];
Rdddd[a,b,c,d]=simplifyroutine[term1],{i,1,Length[selectindices]}];

genconditions[list:{a_,b_,c_,d_}]:=Or@@(Less@@#1&)/@{{a,b,c,d},{b,a,d,c},{c,d,a,b},{d,c,b,a}};

Do[term1=Rdddd@@bindices[Sort[{a,b,c,d}]];term2=Rdddd@@bindices[Sort[{a,b,c,d}][[{1,3,2,4}]]];array[[a,b,c,d]]=
Switch[{a,b,c,d},
{a_,a_,_,_}|{_,_,c_,c_},0,

{a_,b_,a_,b_}/;a<b,Rdddd@@bindices[{a,b,a,b}],
{a_,b_,a_,b_}/;b<a,Rdddd@@bindices[{b,a,b,a}],
{a_,b_,b_,a_}/;a<b,-Rdddd@@bindices[{a,b,a,b}],
{a_,b_,b_,a_}/;b<a,-Rdddd@@bindices[{b,a,b,a}],

{a_,b_,a_,d_}/;b<d,Rdddd@@bindices[{a,b,a,d}],
{a_,b_,a_,d_}/;d<b,Rdddd@@bindices[{a,d,a,b}],
{a_,b_,c_,a_}/;b<c,-Rdddd@@bindices[{a,b,a,c}],
{a_,b_,c_,a_}/;c<b,-Rdddd@@bindices[{a,c,a,b}],
{a_,b_,b_,d_}/;a<d,-Rdddd@@bindices[{b,a,b,d}],
{a_,b_,b_,d_}/;d<a,-Rdddd@@bindices[{b,d,b,a}],
{a_,b_,c_,b_}/;a<c,Rdddd@@bindices[{b,a,b,c}],
{a_,b_,c_,b_}/;c<a,Rdddd@@bindices[{b,c,b,a}],

{a1_,b1_,c1_,d1_}/;genconditions[{a1,b1,c1,d1}],term1,
{a1_,b1_,c1_,d1_}/;genconditions[{a1,b1,d1,c1}],-term1,
{a1_,b1_,c1_,d1_}/;genconditions[{a1,c1,b1,d1}],term2,
{a1_,b1_,c1_,d1_}/;genconditions[{a1,d1,b1,c1}],-term2,
{a1_,b1_,c1_,d1_}/;genconditions[{a1,d1,c1,b1}],term1-term2,
{a1_,b1_,c1_,d1_}/;genconditions[{a1,c1,d1,b1}],term2-term1,
_,Null],
{a,1,ndim},{b,1,ndim},{c,1,ndim},{d,1,ndim}];

+array]


ricciindex=3;
SyntaxInformation[SetRicciContraction]={"ArgumentsPattern"->{_}};
SetRicciContraction[index_?(MatchQ[#, 3|4]&)]:=Set[ricciindex,index];


SyntaxInformation[CalculateRRRG]={"ArgumentsPattern"->{_,_,_.,_.}};
CalculateRRRG[g_,riemmandarray_,flavor_:Identity,simplifyroutine_:Identity]:=
Module[{riemann,ricci,curvaturescalar,einstein,upmetric,downmetric,a,b},
upmetric=g@Global`uu[a,b]//ToFlavor[flavor]//ToArrayValues[];
downmetric=g@Global`dd[a,b]//ToFlavor[flavor]//ToArrayValues[];
riemann=Map[simplifyroutine,upmetric.riemmandarray,{4}];
ricci=Map[simplifyroutine,ContractArray[riemann, {1,ricciindex}],{2}];
curvaturescalar=simplifyroutine[ContractArray[upmetric.ricci,{1,2}]];
einstein=Map[simplifyroutine,ricci-1/2curvaturescalar downmetric,{2}];
{riemann,ricci,curvaturescalar,einstein}
]


SyntaxInformation[CalculateWeyldown]={"ArgumentsPattern"->{_,_,_,_,_.}};
CalculateWeyldown[metric_?MatrixQ,riemann_?ArrayQ,ricci_?MatrixQ,Rscalar_,simplifyroutine_:Identity]:=
Module[{term1,term2},
term1=(-Transpose[Outer[Times,metric,metric],{1,4,3,2}]+Transpose[Outer[Times,metric,metric],{1,3,4,2}])Rscalar/6;
term2=1/2(
-Transpose[Outer[Times,metric,ricci],{2,4,3,1}]+Transpose[Outer[Times,metric,ricci],{1,4,3,2}]+Transpose[Outer[Times,metric,ricci],{2,3,4,1}]-Transpose[Outer[Times,metric,ricci],{1,3,4,2}]);
simplifyroutine[riemann+term1+term2]
]


SyntaxInformation[CovariantCommutator]={"ArgumentsPattern"->{{_,_},_,_}};
CovariantCommutator[{c1_,c2_},R_,d_][term_]:=
Module[{dummies,ups,downs,bads,upterm,downterm},
{dummies,{ups,downs},bads}=ParseTermIndices[term];
If[bads=!={},Message[CovariantCommutator::indices,term,bads];Abort[]];
upterm[i_]:=-Tensor[R,{i,Void,Void,Void},{Void,d,c1,c2}](term//IndexChange[{i,d}]);
downterm[i_]:=Tensor[R,{d,Void,Void,Void},{Void,i,c1,c2}](term//IndexChange[{i,d}]);
Fold[#1+upterm[#2]&,Fold[#1+downterm[#2]&,0,downs],ups]
]


SyntaxInformation[OrthonormalTransformation]={"ArgumentsPattern"->{_,_,_.,_.}};
OrthonormalTransformation[metric_?ArrayQ/;metric==DiagonalMatrix[Tr[metric,List]],signature:{(-1|1)..},simplifyroutine_:Identity,samplevalues_:None]:=
Module[{diagonal,signs,goodsigns=False,Lmatrix},
diagonal=Tr[metric,List];

signs=simplifyroutine@Sign[diagonal];
If[\[Not]MatchQ[signs,{(-1|1)..}]\[And]MatchQ[samplevalues,{Rule[_,_]..}],signs=signs/.samplevalues];
If[MatchQ[signs,{(-1|1)..}]\[And]signs===signature,goodsigns=True,Message[OrthonormalTransformation::signs,signs,signature]];

Lmatrix=DiagonalMatrix[simplifyroutine[1/Sqrt[diagonal signature]]]
];


OrthonormalTransformation[metric_?ArrayQ,signaturein:{(-1|1)..},simplifyroutine_:Identity,samplevalues_:None]:=
Module[{eigenvalues,eigenvectors,signs,scalematrix,Lmatrix,permmatrix,sortfunction,originalsigns,goodsigns=False,signature=signaturein},

{eigenvalues,eigenvectors}=Eigensystem[metric];

signs=simplifyroutine@Sign[eigenvalues];
If[\[Not]MatchQ[signs,{(-1|1)..}]\[And]MatchQ[samplevalues,{Rule[_,_]..}],signs=signs/.samplevalues];
originalsigns=signs;

sortfunction=If[First[signature]==-1,#1<=#2&,#2<=#1&];
signature=Sort[signature,sortfunction];
signs=Sort[signs,sortfunction];
If[MatchQ[signs,{(-1|1)..}]\[And]signs===signature,goodsigns=True,Message[OrthonormalTransformation::signs,signs,signature]];

permmatrix=Transpose@If[goodsigns,Part[IdentityMatrix[NDim],Ordering[originalsigns,NDim,sortfunction]],IdentityMatrix[NDim]];

scalematrix=DiagonalMatrix[simplifyroutine[1/Sqrt[originalsigns*eigenvalues]]];
Lmatrix=Map[simplifyroutine,Transpose[#/Sqrt[#.#]&/@eigenvectors],{2}];
Map[simplifyroutine,Lmatrix.scalematrix.permmatrix,{2}]
]


SyntaxInformation[LorentzTransformation]={"ArgumentsPattern"->{_,{_,_,_}}};
LorentzTransformation[\[Beta]_,nvect:{_,_,_}]:=
Module[{L=IdentityMatrix[4],\[Gamma]=1/Sqrt[1-\[Beta]^2],n=Normalize[nvect],j,k},
Part[L,1,1]=\[Gamma];
Do[Part[L,1,j+1]=Part[L,j+1,1]=-\[Beta] \[Gamma] Part[n,j],{j,1,3}];
Do[Part[L,j+1,k+1]=Part[L,k+1,j+1]=(\[Gamma]-1) Part[n,j]Part[n,k]+KroneckerDelta[j,k],{j,1,3},{k,1,3}];
L]


SyntaxInformation[PartialD]={"ArgumentsPattern"->{__}};
SyntaxInformation[ExpandPartialD]={"ArgumentsPattern"->{{_,_,_,_}}};
SyntaxInformation[NondependentPartialD]={"ArgumentsPattern"->{__}};
SyntaxInformation[UsePartialDChainRule]={"ArgumentsPattern"->{__}};


PartialD[{x_,\[Delta]_,g_,\[CapitalGamma]_}][w_List,v__]:= Map[PartialD[{x,\[Delta],g,\[CapitalGamma]}][#,v] &, w];


(* ::Input:: *)
PartialD[expr_,__]/;FreeQ[{expr},Tensor[__]]:=0


PartialD[expr_,indices__]/;\[Not]Expand[expr]===expr:=PartialD[Expand[expr],indices]


PartialD[a_+b_,indices_]:= PartialD[a,indices]+PartialD[b,indices]
PartialD[a_ t1_,indices_]/;FreeQ[{a},Tensor[__]]:=a PartialD[t1,indices]


PartialD[t1_ t2__,l_List]/;Length[l]>1:=PartialD[PartialD[t1 t2,Rest[l]],First[l]]


PartialD[(t1_Tensor|t1_PartialD) t2__,{i_?SymbolicIndexQ}|i_?SymbolicIndexQ]:=PartialD[t1,i]t2+t1 PartialD[Times@@{t2},i]


PartialD[HoldPattern[PartialD[t_,i_?SymbolicIndexQ]],j_?SymbolicIndexQ]:=PartialD[t,{i,j}]


PartialD[HoldPattern[PartialD[t_,l_List]],j_]:=PartialD[t,Flatten[{l,j}]]


PartialD[Dot[w_ ,u_],j_]:=Dot[PartialD[w,j], u]+Dot[PartialD[u,j] ,w]/;VectorQ[j]===False;


PartialD[{x_,\[Delta]_,_,_}][TotalD[Tensor[x_,{a_},{Void}],t_],Tensor[x_,{b_},{Void}]]:=0


ExpandPartialD[{x_,\[Delta]_,g_,\[CapitalGamma]_}][expr_]:=
expr/.
{HoldPattern[PartialD[t_Tensor,index_?SymbolicIndexQ]]:>PartialD[{x,\[Delta],g,\[CapitalGamma]}][t,Tensor[x,{index},{Void}]],
HoldPattern[PartialD[t_Tensor,indices:{__?SymbolicIndexQ}]]:>PartialD[{x,\[Delta],g,\[CapitalGamma]}][t,Tensor[x,{#},{Void}]&/@indices]}


PartialD[{x_,\[Delta]_,g_,\[CapitalGamma]_}][w_,v_List]:=D[w,Sequence@@v]/;FreeTensorQ[w]&&(And@@Map[FreeTensorQ[#]&,v]);


PartialD[{x_,\[Delta]_,g_,\[CapitalGamma]_}][w_,v_]:=D[w,v]/;FreeTensorQ[w]&&FreeTensorQ[v]


PartialD[{x_,\[Delta]_,g_,\[CapitalGamma]_}][s_SeriesData,v_List]:=D[s,Sequence@@v];


PartialD[{x_,\[Delta]_,g_,\[CapitalGamma]_}][s_SeriesData,v_]:=D[s,v]


PartialD[labs_List][a_ b_,c_]/;FreeQ[a,Tensor[__]|c]\[And]FreeQ[c,Tensor[__]]:=a PartialD[labs][b,c]


(* ::Input:: *)
PartialD[_][ a_?NumericQ  , _ ] := 0;


PartialD[_][u_Symbol,v__ ]:=0/;MemberQ[Attributes[u],Constant]


(* ::Input:: *)
PartialD[labels_][ T_Plus , v_ ]:= PartialD[labels][#,v]& /@ T;


HoldPattern[PartialD[labels_][Dot[w_ ,u_],j_]]:=Dot[PartialD[labels][w,j], u]+Dot[PartialD[labels][u,j] ,w]/;VectorQ[j]===False;


(* ::Input:: *)
PartialD[labels_][ T_*U_ , v_ ]:= PartialD[labels][T,v]*U + T*PartialD[labels][U,v]/;VectorQ[v]==False;


PartialD[w_ ,{}]:=w;


PartialD[labs_][w_ ,{}]:=w;


PartialD[w_ ,{i_}]:=PartialD[w ,i];


PartialD[labs_][w_ ,{i_}]:=PartialD[labs][w,i];


PartialD[labs_][T_,u_List]/;\[Not]OrderedQ[u]:=PartialD[labs][T,Sort[u]]


(* ::Input:: *)
PartialD[{x_,\[Delta]_,g_,\[CapitalGamma]_}][ Tensor[x_,{i_},{Void}] ,Tensor[x_,{j_},{Void}] ]/;(Head[i]===Head[j]&&Not[VectorQ[j]])=Tensor[\[Delta],{i,Void},{Void,j}];


(* ::Input:: *)
PartialD[{x_,\[Delta]_,g_,\[CapitalGamma]_}][ Tensor[x_,{Void},{i_}] ,Tensor[x_,{Void},{j_}] ]/;(Head[i]===Head[j]&&Not[VectorQ[j]])=Tensor[\[Delta],{j,Void},{Void,i}];


FilterPD[Void,Void]:=Sequence[];
FilterPD[i_,Void]:=i;
FilterPD[Void,i_]:=i;
HoldPattern[PartialD[{x_,\[Delta]_,g_,\[CapitalGamma]_}][ Tensor[x_,U1:{__},U2_] ,Tensor[x_,V__] ]]:=Module[{ind},
ind=MapThread[FilterPD,MapAt[  Reverse[#]&,{{U1,U2},{V}},2],2];
Times@@Map[Tensor[\[Delta],{#[[1]],Void},{Void,#[[2]]}]&,Transpose[ind]  ]
]/;(Count[ind=MapThread[FilterPD,MapAt[  Reverse[#]&,{{U1,U2},{V}},2],2],FilterPD[__],2]==0)&&(And@@MapThread[(Head[#1]===Head[#2])&,Append[Transpose[ind],{1,2}]  ])



(* ::Input:: *)
PartialD[{x_,\[Delta]_,g_,\[CapitalGamma]_}][Tensor[\[Delta]_,__],_]:=0


PartialD[{x_,\[Delta]_,g_,\[CapitalGamma]_}][Tensor[x_,{i_},{Void}],{___,Tensor[x_,{j_},{Void}],___,Tensor[x_,{k_},{Void}],___}]/;Head[i]===Head[j]\[And]Head[i]===Head[k]=0;


PartialD[{x_,_,_,_}][expr_,expr_]/;\[Not]MatchQ[expr, Tensor[x,{i_},{Void}]]:=1


PartialD[labels_][   HoldPattern[PartialD[labels_][    T_ , u_ ]] , v_ ]:=PartialD[labels][   T ,Flatten[{v,u}] ];


PartialD[labels_][T_Times ,u_List]:=Fold[ PartialD[labels][  #1 ,#2 ]&,T,u];


HoldPattern[PartialD[lab_][ f_[g_],t_List]]:= Fold[  PartialD [lab][#1,#2]&  ,  f[g]  , t   ] /;Not[MemberQ[{Tensor,TotalD,AbsoluteD,LieD,CovariantD},f]];


HoldPattern[PartialD[lab_][  F_[g_]  ,T_ ]]:=Derivative[1][F][g]*PartialD[lab][ g,T  ]/;Not[MemberQ[{Tensor,TotalD,AbsoluteD,LieD,CovariantD},F]\[Or]MatchQ[g,Tensor[Part[lab,1],{i_?(\[Not]BaseIndexQ[#]&)},{Void}] ]];


HoldPattern[PartialD[lab_][  Power[g_,n_]  ,T_ ]]:=Derivative[1,0][Power][g,n]*PartialD[lab][ g,T  ]+Derivative[0,1][Power][g,n]*PartialD[lab][ n,T  ]/;Not[VectorQ[T]]


HoldPattern[PartialD[lab_][  Power[g_,n_]  ,{T_,S__}]]:=
PartialD[lab][
Derivative[1,0][Power][g,n]*PartialD[lab][ g,T  ]+Derivative[0,1][Power][g,n]*PartialD[lab][ n,T  ]
,{S}]


HoldPattern[ PartialD[lab_][ f_[g__],{t_,s__}] ]:= 
PartialD[lab][   PartialD[lab][f[g],t]   ,{s}]/;Not[MemberQ[{Tensor,TotalD,AbsoluteD,LieD,CovariantD},f]]&&Not[MatchQ[f,PartialD[_]]];


HoldPattern[PartialD[lab_][ f_[g__],t_ ]
]:=Plus@@MapThread[Derivative[Sequence@@#1][f][g]PartialD[lab][#2,t]&,{IdentityMatrix[Length[{g}]],{g}}]/;Not[MemberQ[{Tensor,TotalD,AbsoluteD,LieD,CovariantD},f]]&&Not[MatchQ[f,PartialD[_]]]&&Not[VectorQ[t]]&&Not[Length[{g}]==1\[And]MatchQ[g,Tensor[Part[lab,1],{i_?(\[Not]BaseIndexQ[#]&)},{Void}] ]];


NondependentPartialD[qin__?VectorQ][expr_]:=
Module[{partialtest,q={qin}},

partialtest[t_,partialsin_]:=
Module[{partials,partiallabs},
partials=If[Head[partialsin]===List,partialsin,{partialsin}];
partiallabs=Cases[partials, Tensor[lab_,___]->lab];

Or@@(If[MemberQ[#,t],Intersection[Complement[#,{t}],partiallabs]=!={},False]&/@q)
];

expr/.PartialD[_][Tensor[t_,ind___],p_]/;partialtest[t,p]:>0
]


UsePartialDChainRule[coordtensor_][expr_]:=
expr/.HoldPattern[PartialD[labs_][x_Tensor,y_]]->PartialD[labs][x,coordtensor]PartialD[labs][coordtensor,y]


UsePartialDChainRule[diffvar1_,diffvar2_][expr_]:=
expr/.{HoldPattern[PartialD[labs_][x_Tensor,diffvar2]]->PartialD[labs][x,diffvar1]PartialD[labs][diffvar1,diffvar2],
HoldPattern[PartialD[labs_][x_Tensor,{varsa___,diffvar2,varsb___}]]->PartialD[labs][x,{varsa,diffvar1,varsb}]PartialD[labs][diffvar1,diffvar2]}


SyntaxInformation[CovariantD]={"ArgumentsPattern"->{_,__}};
SyntaxInformation[ExpandCovariantD]={"ArgumentsPattern"->{{_,_,_,_},_,_.}};
SyntaxInformation[BasisExpandCovariantD]={"ArgumentsPattern"->{{_,_,_,_},_,_.}};


CovariantD[tensor_,i_?SymbolicIndexQ]:=CovariantD[tensor,{Void},{i}]
CovariantD[tensor_,downs:{(_?SymbolicIndexQ)..}]:=
Module[{l=Length[downs]},
CovariantD[tensor,Table[Void,{l}],downs]
]
CovariantD[tensor_,(f_?udsymQ)[indices__]]:=CovariantD[tensor,f[indices]//Parseud]


CovariantD[expr_,__]/;FreeQ[{expr},Tensor[__]]:=0


CovariantD[expr_,indices__]/;\[Not]Expand[expr]===expr:=CovariantD[Expand[expr],indices]


CovariantD[HoldPattern[CovariantD[expr_,iup_,idown_]],jup_,jdown_]:=CovariantD[expr,Join[iup,jup],Join[idown,jdown]]


CovariantD[a_+b_,indices__]:= CovariantD[a,indices]+CovariantD[b,indices]
CovariantD[a_ t1_,indices__]/;FreeTensorQ[a]:=a CovariantD[t1,indices]


CovariantD[(t1_Tensor | t1_CovariantD) t2_, {upi_},{downi_}]  := CovariantD[t1,{upi},{downi}]t2 + t1*CovariantD[t2,{upi},{downi}]


CovariantD[(t1_Tensor | t1_CovariantD) t2_, upi_,downi_]  := Module[{firstind,restind,allinds},
allinds=Transpose[{upi,downi}];
firstind = {#}&/@First[allinds];
restind= Transpose@Rest[allinds];
CovariantD[
CovariantD[ t1*t2 ,Sequence@@firstind],Sequence@@restind]
]


ExpandCovariantD[labels_,{a_},permissive_:False][T_]:=ExpandCovariantD[labels,a,permissive][T];


ExpandCovariantD[labels_,a_,permissive_:False][HoldPattern[CovariantD[Tensor[T_],{Void},{j_}]]/;!VectorQ[j]\[And]FreeQ[T,Tensor]]:=ExpandPartialD[labels][PartialD[Tensor[T],j]]


AllowedCovariantD[{_,_,_,\[CapitalGamma]_},permissive_][expr_]:=
Module[{count,covariantargs=Cases[{expr},HoldPattern[CovariantD[ten_,__]]->ten,\[Infinity]]//Flatten},
(* We don't allow unexpanded partials or tensors with base indices *)
count=Count[covariantargs,HoldPattern[PartialD[Tensor[__],_]]|Tensor[_,{___,_?BaseIndexQ,___},_]|Tensor[_,_,{___,_?BaseIndexQ,___}],\[Infinity]];
(* If not permissive we don't allow expanded partials or Christoffels *)
If[\[Not]permissive,
count=count+Count[covariantargs,HoldPattern[PartialD[_][Tensor[__],_]] |Tensor[\[CapitalGamma],{_,_,_},{_,_,_}],\[Infinity]]
];
If[count>0,Message[ExpandCovariantD::nottensor,expr];Abort[]];
True
]


ExpandCovariantD[labs_,indices_,permissive_:False][expr_]/;(AllowedCovariantD[labs,permissive][expr])\[And]\[Not](SameQ[temp=Expand[expr],expr]):=ExpandCovariantD[labs,indices,permissive][temp]


ExpandCovariantD[labs_,indices_,permissive_:False][expr_]/;MatchQ[Head[expr],List|Plus|Equal|LessEqual|GreaterEqual|Less|Greater|Unequal]:=ExpandCovariantD[labs,indices,permissive]/@expr


ExpandCovariantD[labs:{x_,\[Delta]_,g_,\[CapitalGamma]_},newindices_,permissive_:False][expr_]:=
Module[{wexpr=expr,order,windices=Flatten[{newindices}],workproduct,processterm,afact},
order=Length[windices];

processterm[term_]:=
Switch[term,

a_. (c1_CovariantD c2__CovariantD)/;FreeQ[{a},CovariantD]\[And]
Module[{indices,tempworkproduct},
tempworkproduct=List@@(c1 c2);
indices=Flatten[{{Part[#,2],Part[#,3]}&/@tempworkproduct}];
If[Length[indices]==2*order,workproduct=tempworkproduct;afact=a;True,False]],afact CovariantDD[labs][workproduct,windices],

a_. HoldPattern[single:CovariantD[_,__]]/;FreeQ[{a},CovariantD]\[And]Module[{indices,tempworkproduct},
tempworkproduct=List@single;
indices=Flatten[{{Part[#,2],Part[#,3]}&/@tempworkproduct}];
If[Length[indices]==2*order,workproduct=tempworkproduct;afact=a;True,False]],afact CovariantDD[labs][workproduct,windices],

_,term  ];

wexpr=If[Head[wexpr]===Plus,processterm/@wexpr,processterm[wexpr]];
wexpr/.CovariantDD->CovariantDE
]


CovariantDE[labs_][tlist_List,indexlist_List]:=
Module[{worklist={},windices=indexlist,cd,indx,i,nindices},
Do[cd=Part[tlist,i];
nindices=Length@Flatten[{Part[cd,3]}];
indx=Take[windices,nindices];
windices=Drop[windices,nindices];
worklist={worklist,CovariantDE[labs][cd,indx]},{i,1,Length[tlist]}];
Times@@Flatten[worklist]
]


CovariantToChristoffel[labs:{x_,_,_,\[CapitalGamma]_},{covindex_,dummyindex_}][{expr_,freeups_,freedowns_}]:=
Module[{upterms=0,downterms=0,windex,i},
If[Length[freeups]>0,
upterms=Plus@@Table[windex=Part[freeups,i];Tensor[\[CapitalGamma],{windex,Void,Void},{Void,covindex,dummyindex}](expr//IndexChange[{windex,dummyindex}]),{i,1,Length[freeups]}]];
If[Length[freedowns]>0,
downterms=Plus@@Table[windex=Part[freedowns,i];Tensor[\[CapitalGamma],{dummyindex,Void,Void},{Void,covindex,windex}](expr//IndexChange[{windex,dummyindex}]),{i,1,Length[freedowns]}]];
{PartialD[labs][expr,Tensor[x,{covindex},{Void}]]+upterms-downterms,freeups,Flatten[{freedowns,covindex}]}
]


CovariantDE[labs_][HoldPattern[CovariantD[tensor:Tensor[_,_,_],up_,cindx_]],{dindx_}]:= 
If[ up==={Void},
First@CovariantToChristoffel[labs,{If[Head[cindx]===List,First[cindx],cindx],dindx}][{tensor,Sequence@@ExtractFreeIndices[tensor]}], 
Print[Style["CovariantExpansion:: CovariantExpansion does not expand contravariant derivatives ",Red]];Hold@ExpandCovariantD[labs][CovariantD[tensor,up,cindx],{dindx}]
]


CovariantDE[labs_][HoldPattern[CovariantD[tensor:Tensor[_,_,_],up_,covindices_List]],dummyindices_List]:=
If[Union[up]==={Void},
First@Fold[CovariantToChristoffel[labs,#2][#1]&,{tensor,Sequence@@ExtractFreeIndices[tensor]},Transpose[{covindices,dummyindices}]]
,
Print[Style["CovariantExpansion:: CovariantExpansion does not expand contravariant derivatives ",Red]];Hold@ExpandCovariantD[labs][CovariantD[tensor,up,cindx],{dindx}]
]


CovariantDE[labs_][HoldPattern[CovariantD[partial:PartialD[labs_][tensor_,coords_],up_,cindx_]],{dindx_}]:= First@CovariantToChristoffel[labs,{If[Head[cindx]===List,First[cindx],cindx],dindx}][{partial,Sequence@@ExtractFreeIndices[partial]}]


CovariantDE[labs_][HoldPattern[CovariantD[partial:PartialD[labs_][tensor_,coords_],up_,covindices_List]],dummyindices_List]:=First@Fold[CovariantToChristoffel[labs,#2][#1]&,{partial,Sequence@@ExtractFreeIndices[partial]},Transpose[{covindices,dummyindices}]]


CovariantDE[labs_][HoldPattern[CovariantD[tensor:Tensor[_],up_,covindices_List]],dummyindices_List]:=First@Fold[CovariantToChristoffel[labs,#2][#1]&,{tensor,Sequence@@ExtractFreeIndices[tensor]},Transpose[{covindices,dummyindices}]]


BasisExpandCovariantD[labs_,indices_][expr_]:=
Module[{work,baserules={},basesubstitute,b=Global`b},
basesubstitute[q_]:=Tensor[lab_,up_,down_]:>
Module[{newups=up,newdowns=down,qvar},
newups=If[\[Not]BaseIndexQ[#],#,
qvar=Unique[q];
baserules=Join[baserules,{qvar->#}];
qvar]&/@newups;
newdowns=If[\[Not]BaseIndexQ[#],#,
qvar=Unique[q];
baserules=Join[baserules,{qvar->#}];
qvar]&/@newdowns;
Tensor[lab,newups,newdowns]
];
work=expr/.basesubstitute[b];
work=work//ExpandCovariantD[labs,indices];
work/.baserules
]


SyntaxInformation[TotalD]={"ArgumentsPattern"->{__}};
SyntaxInformation[ExpandTotalD]={"ArgumentsPattern"->{{_,_,_,_},_}};
SyntaxInformation[UseTotalDChainRule]={"ArgumentsPattern"->{_,_}};


TotalD[CircleTimes[args__],t__]:=
Module[{n=Length[{args}],i},
Sum[CircleTimes@@Join[Part[{args},Range[1,i-1]],{TotalD[Part[{args},i],t]},Part[{args},Range[i+1,n]]],{i,1,n}]]


TotalD[w_List,j_]:=(TotalD[#1,j]&)/@w;


TotalD[w_List]:=(TotalD[#1]&)/@w;


TotalD[w_Equal,j_]:=(TotalD[#1,j]&)/@w;


TotalD[w_Equal]:=(TotalD[#1]&)/@w;


(* ::Input:: *)
TotalD[u_?NumericQ,___]:=0;


(* ::Input:: *)
TotalD[u_,u_]:=1;


(* ::Input:: *)
TotalD[u_Symbol,v___]:=0/;MemberQ[Attributes[u],Constant];


TotalD[w_Plus,j_]:=(TotalD[#1,j]&)/@w;


TotalD[w_Plus]:=(TotalD[#1]&)/@w;


TotalD[w_*u_,j_]:=TotalD[w,j] u+TotalD[u,j] w/;VectorQ[j]==False;


TotalD[w_*u_]:=TotalD[w] u+TotalD[u] w/;VectorQ[j]==False;


TotalD[w_?FreeTensorQ,t_]:=Dt[w,t]/;(Head[w]=!=PartialD)&&(Head[w]=!=TotalD)&&(Head[Head[w]]=!=PartialD)&&Not[VectorQ[t]];


TotalD[CircleTimes[args__]]:=
Module[{n=Length[{args}],i},
Sum[CircleTimes@@Join[Part[{args},Range[1,i-1]],{TotalD[Part[{args},i]]},Part[{args},Range[i+1,n]]],{i,1,n}]]


TotalD[w_?FreeTensorQ]:=Dt[w]/;(Head[w]=!=PartialD)&&(Head[w]=!=TotalD)&&(Head[Head[w]]=!=PartialD)&&Not[VectorQ[t]];


TotalD[ Power[g_,n_],t_ ]:=(Derivative[ 1 ,0  ][Power][g,n]TotalD[ g,t]+Derivative[ 0 ,1  ][Power][g,n]TotalD[ n,t])/;Not[VectorQ[t]];


TotalD[ Power[g_,n_]]:=(Derivative[ 1 ,0  ][Power][g,n]TotalD[ g]+Derivative[ 0 ,1  ][Power][g,n]TotalD[ n]);


TotalD[ f_[g_],t_ ]:=Derivative[1][f][g]TotalD[g,t]/;f=!=Tensor&&f=!=Times&&f=!=Plus&&f=!=TotalD&&Not[MatchQ[f,PartialD[_]]]&&Not[VectorQ[t]];


TotalD[ f_[g_]]:=Derivative[1][f][g]TotalD[g]/;Not[MemberQ[{Tensor,Times,Plus,TotalD,AbsoluteD,LieD},f]]&&Not[MatchQ[f,PartialD[_]]];


TotalD[ f_[g__],t_ ]:=Plus@@MapThread[Derivative[Sequence@@#1][f][g]TotalD[#2,t]&,{IdentityMatrix[Length[{g}]],{g}}]/;Not[MemberQ[{Tensor,Times,Plus,TotalD,AbsoluteD,LieD},f]]&&Not[MatchQ[f,PartialD[_]]]&&Not[VectorQ[t]];


TotalD[ f_[g__]]:=Plus@@MapThread[Derivative[Sequence@@#1][f][g]TotalD[#2]&,{IdentityMatrix[Length[{g}]],{g}}]/;Not[MemberQ[{Tensor,Times,Plus,TotalD,AbsoluteD,LieD},f]]&&Not[MatchQ[f,PartialD[_]]];


TotalD[w_*u_,j_List]:=Fold[ TotalD[#1,#2]&,w*u,j];


TotalD[   HoldPattern[TotalD[    T_ , u_ ]] , v_ ]:=TotalD[   T ,Flatten [{u,v}]  ];


TotalD[T_ ,u_List]:=Fold[  TotalD[  #1 ,#2 ]& ,T,u]/;Head[T]=!=Tensor;


ExpandTotalD[args__][expr_/;MemberQ[{List,Equal,Plus,Less,Greater,LessEqual,GreaterEqual}, Head[expr]]]:=ExpandTotalD[args]/@expr


ExpandTotalD[labels_,dummy_][T_?NumericQ*V_]:=T* ExpandTotalD[labels,dummy][V];


ExpandTotalD[{x_,\[Delta]_,g_,\[CapitalGamma]_},dummy_][    HoldPattern[TotalD[ Tensor[x_,ind__] ,t_]*V_]     ]:=TotalD[ Tensor[x,ind] ,t]* ExpandTotalD[{x,\[Delta],g,\[CapitalGamma]},dummy][V];


ExpandTotalD[labels_,dummy_][T_*V_]:=T* ExpandTotalD[labels,dummy][V]/;FreeTotalDQ[T];


ExpandTotalD[labels_,dummy_][T_]:=T/;FreeTotalDQ[T];


ExpandTotalD[labels_,{a_,dummy__}][T_*V_]:=ExpandTotalD[labels,a][T]*ExpandTotalD[labels,{dummy}][V]/;Not[FreeTotalDQ[T]]&&Not[FreeTotalDQ[V]];


ExpandTotalD[x_,{a_}][T_]:=ExpandTotalD[x,a][T];


ExpandTotalD[{x_,\[Delta]_,g_,\[CapitalGamma]_},dummy_][   HoldPattern[TotalD[T_,v_]]   ]:=PartialD[{x,\[Delta],g,\[CapitalGamma]}][T,Tensor[x,{dummy},{Void}]]*TotalD[ Tensor[x,{dummy},{Void}]  ,v]/;Not[VectorQ[v]]&&Not[VectorQ[dummy]];


ExpandTotalD[{x_,\[Delta]_,g_,\[CapitalGamma]_},dummy_][HoldPattern[TotalD[T_]]]:=PartialD[{x,\[Delta],g,\[CapitalGamma]}][T,Tensor[x,{dummy},{Void}]] TotalD[Tensor[x,{dummy},{Void}]]/;!VectorQ[dummy];


ExpandTotalD[{x_,\[Delta]_,g_,\[CapitalGamma]_},dummy_List][HoldPattern[TotalD[T_,v_List]]]:=Module[{DummyParam},
If[Length[dummy]=!=Length[v],Message[ExpandTotalD::dummies,dummy,v];Abort[]];
DummyParam=Transpose[{dummy,v}];Fold[ExpandTotalD[{x,\[Delta],g,\[CapitalGamma]},#2[[1]]][TotalD[#1,#2[[2]]]]&,T,DummyParam]];


ReversePartialTotalChainRule:={HoldPattern[PartialD[{x_,\[Delta]_,_,_}][TotalD[t_Tensor,u_],Tensor[x_,{\[Mu]_},{Void}]]TotalD[Tensor[x_,{\[Mu]_},{Void}],v_]]:>TotalD[t,{u,v}],
HoldPattern[PartialD[{x_,\[Delta]_,_,_}][TotalD[t_Tensor,u_],Tensor[x_,{\[Mu]_},{Void}]]TotalD[Tensor[x_,{\[Mu]_},{Void}]]]:>TotalD[t,u],
HoldPattern[PartialD[{x_,\[Delta]_,_,_}][t_Tensor,Tensor[x_,{\[Mu]_},{Void}]]TotalD[Tensor[x_,{\[Mu]_},{Void}]]]:>TotalD[t]}


UseTotalDChainRule[coordtensor_,labels_][expr_]:=
expr/.HoldPattern[TotalD[x_,y_]]->PartialD[labels][x,coordtensor]TotalD[coordtensor,y]


SyntaxInformation[AbsoluteD]={"ArgumentsPattern"->{_,_}};
SyntaxInformation[ExpandAbsoluteD]={"ArgumentsPattern"->{{_,_,_,_},_,_.}};


AbsoluteD[expr_,__]/;FreeQ[{expr},Tensor[__]]:=0


AbsoluteD[expr_,difvars__]/;\[Not]Expand[expr]===expr:=AbsoluteD[Expand[expr],difvars]


AbsoluteD[a_+b_,difvars_]:=AbsoluteD[a,difvars]+AbsoluteD[b,difvars]
AbsoluteD[a_ t1_,difvars_]/;FreeQ[{a},Tensor[__]]:=a AbsoluteD[t1,difvars]


AbsoluteD[t1_Tensor t2__Tensor,l_List]/;Length[l]>1:=AbsoluteD[AbsoluteD[t1 t2,Drop[l,-1]],Last[l]]
AbsoluteD[(t1_Tensor|t1_AbsoluteD|t1_TotalD) t2__,{i_}|i_]:=AbsoluteD[t1,i]t2+t1 AbsoluteD[Times@@{t2},i]

AbsoluteD[HoldPattern[AbsoluteD[t_,i_]],j_]:=AbsoluteD[t,{i,j}]
AbsoluteD[AbsoluteD[t_,l_List],j_]:=AbsoluteD[t_,Flatten[{l,j}]]


AbsoluteD[Tensor[T_],j_]/;!VectorQ[j]\[And]FreeQ[T,Tensor]:=TotalD[Tensor[T],j];
AbsoluteD[Tensor[T_],{j_}]:=TotalD[Tensor[T],j];


AllowedAbsoluteD[{_,_,_,\[CapitalGamma]_},permissive_][expr_]:=
Module[{count,absoluteargs=Cases[{expr},HoldPattern[AbsoluteD[ten_,_]]->ten,\[Infinity]]//Flatten},
(* We don't allow partials or tensors with base indices *)
count=Count[absoluteargs,
HoldPattern[PartialD[Tensor[__],_]]|HoldPattern[PartialD[_][Tensor[__],_]] |
Tensor[_,{___,_?BaseIndexQ,___},_]|Tensor[_,_,{___,_?BaseIndexQ,___}],\[Infinity]];
(* Christoffels and total derivatives are allowed only if permissive *)
If[\[Not]permissive,
count=count+
Count[absoluteargs,Tensor[\[CapitalGamma],{_,_,_},{_,_,_}]|HoldPattern[TotalD[_,_]]]];
If[count>0,Message[ExpandAbsoluteD::nottensor,expr];Abort[]];
True
]


ExpandAbsoluteD[labs_,difvars_,permissive_:False][expr_]/;MatchQ[Head[expr],List|Plus|Equal|LessEqual|GreaterEqual|Less|Greater|Unequal]:=ExpandAbsoluteD[labs,difvars,permissive]/@expr


ExpandAbsoluteD[labs_,difvars_,permissive_:False][expr_]/;(AllowedAbsoluteD[labs,permissive][expr])\[And]\[Not](SameQ[temp=Expand[expr],expr]):=ExpandAbsoluteD[labs,difvars,permissive][temp]


ExpandAbsoluteD[labs:{x_,\[Delta]_,g_,\[CapitalGamma]_},newindices:{_?SymbolicIndexQ,_?SymbolicIndexQ}|{{_?SymbolicIndexQ,_?SymbolicIndexQ},{_?SymbolicIndexQ,_?SymbolicIndexQ}..},permissive_:False][expr_]:=
Module[{wexpr=expr,order,windices,workproduct,processterm,afact},
windices=If[MatchQ[newindices, {_?SymbolicIndexQ,_?SymbolicIndexQ}],{newindices},newindices];
order=Length[windices];
processterm[term_]:=
Switch[term,

a_. (c1_AbsoluteD c2__AbsoluteD)/;FreeQ[{a},AbsoluteD]\[And]
Module[{difvars,tempworkproduct},
tempworkproduct=List@@(c1 c2);
difvars=Flatten[{Part[#,2]&/@tempworkproduct}];
If[Length[difvars]==order,workproduct=tempworkproduct;afact=a;True,False]],afact AbsoluteDX[labs][workproduct,windices],

a_. HoldPattern[single:AbsoluteD[_,_]]/;FreeQ[{a},AbsoluteD]\[And]Module[{difvars,tempworkproduct},
tempworkproduct=List@single;
difvars=Flatten[{Part[#,2]&/@tempworkproduct}];
If[Length[difvars]==order,workproduct=tempworkproduct;afact=a;True,False]],afact AbsoluteDX[labs][workproduct,windices],

_,term];

wexpr=If[Head[wexpr]===Plus,processterm/@wexpr,processterm[wexpr]];
wexpr/.AbsoluteDX->AbsoluteDE
]


AbsoluteDE[labs_][tlist_List,indexlist_List]:=
Module[{worklist={},windices=indexlist,ad,indx,i,nvars},
Do[ad=Part[tlist,i];
nvars=Length@Flatten[{Part[ad,2]}];
indx=Take[windices,nvars];
windices=Drop[windices,nvars];
worklist={worklist,AbsoluteDE[labs][ad,indx]},{i,1,Length[tlist]}];
Times@@Flatten[worklist]
]


AbsoluteToChristoffel[labs:{x_,_,_,\[CapitalGamma]_},{difvar_,dummyindices:{a_,b_}},{freeups_,freedowns_}][expr_]:=
Module[{upterms=0,downterms=0,windex,i},
If[Length[freeups]>0,
upterms=Plus@@Table[windex=Part[freeups,i];Tensor[\[CapitalGamma],{windex,Void,Void},{Void,a,b}](expr//IndexChange[{windex,a}])TotalD[Tensor[x,{b},{Void}],difvar],{i,1,Length[freeups]}]];
If[Length[freedowns]>0,
downterms=Plus@@Table[windex=Part[freedowns,i];Tensor[\[CapitalGamma],{a,Void,Void},{Void,b,windex}](expr//IndexChange[{windex,a}])TotalD[Tensor[x,{b},{Void}],difvar],{i,1,Length[freedowns]}]];
TotalD[expr,difvar]+upterms-downterms
]


AbsoluteDE[labs_][HoldPattern[AbsoluteD[tensor:Tensor[_,_,_],difvar_Symbol]],{{a_,b_}}]:= AbsoluteToChristoffel[labs,{If[Head[difvar]===List,First[difvar],difvar],{a,b}},ExtractFreeIndices[tensor]][tensor]


AbsoluteDE[labs_][HoldPattern[AbsoluteD[tensor:Tensor[_,_,_],difvars_List]],dummyindices_List]:=Fold[AbsoluteToChristoffel[labs,#2,ExtractFreeIndices[tensor]][#1]&,tensor,Transpose[{difvars,dummyindices}]]


AbsoluteDE[labs_][HoldPattern[AbsoluteD[total:TotalD[tensor_,coords_],difvar_]],{{a_,b_}}]:= AbsoluteToChristoffel[labs,{If[Head[difvar]===List,First[difvar],difvar],{a,b}},ExtractFreeIndices[total]][total]


AbsoluteDE[labs_][HoldPattern[AbsoluteD[total:TotalD[tensor_,coords_],difvars_List]],dummyindices_List]:=Fold[AbsoluteToChristoffel[labs,#2,ExtractFreeIndices[total]][#1]&,total,Transpose[{difvars,dummyindices}]]


SyntaxInformation[LieD]={"ArgumentsPattern"->{_,_}};
SyntaxInformation[ExpandLieD]={"ArgumentsPattern"->{{_,_,_,_},_}};


(* ::Input:: *)
LieD[T_Plus,V_] := Map[ LieD[#,V]& , T ];


(* ::Input:: *)
LieD[u_?NumericQ,__]:=0;


(* ::Input:: *)
LieD[u_Symbol,_]:=0;


LieD[w_Plus,V_]:=(LieD[#1,V]&)/@w;


LieD[w_*u_,V_]:=LieD[w,V] *u+LieD[u,V]* w/;Not[VectorQ[V]];


LieD[w_*u_,V_List]:=Fold[  LieD[#1,#2]&,w*u,V];


LieD[   LieD[T_ , U_] , V_ ]:=LieD[   T ,   Flatten[{U,V}]  ];


LieD[T_ ,U_List]:=Fold[  LieD[  #1 ,#2 ]& ,T,U]/;Head[T]=!=Tensor;


ExpandLieD[args__][expr_]/;\[Not]Expand[expr]===expr:=ExpandLieD[args][Expand[expr]]


ExpandLieD[args__][expr_/;MemberQ[{List,Equal,Plus,Less,Greater,LessEqual,GreaterEqual}, Head[expr]]]:=ExpandLieD[args]/@expr


LieDOrderMatchQ[expr_,dummies_]:=
Module[{work,orderexpr,orderdummies=Length[Flatten[{dummies}]]},
work=expr/.a_+b__/;FreeQ[a, LieD]\[And]FreeQ[b, LieD]->1;
If[\[Not]FreeQ[work, Plus,{0,1}],Return[False]];
orderexpr=Length[Flatten[Cases[work, LieD[_,t_]:>t,{0,1}]]];
orderexpr==orderdummies
]


ExpandLieD[_,dummies_][expr_]/;\[Not]LieDOrderMatchQ[expr,dummies]:=expr;


ExpandLieD[x_,dummy_][T_?NumericQ*V_]:=T* ExpandLieD[x,dummy][V];


ExpandLieD[x_,dummy_][T_*V_]:=T* ExpandLieD[x,dummy][V]/;FreeLieDQ[T];


ExpandLieD[x_,dummy_][T_]:=T/;FreeLieDQ[T];


ExpandLieD[x_,{dummy1_,dummy2__}][T_*V_]:=ExpandLieD[x,dummy1][T]*ExpandLieD[x,{dummy2}][V]/;Not[FreeLieDQ[T]]&&Not[FreeLieDQ[V]];


ExpandLieD[x_,{a_}][T_]:=ExpandLieD[x,a][T];


PartialDFieldV[{x_,\[Delta]_,g_,\[CapitalGamma]_},V_,dummy_][{i_,Void}]:=-PartialD[{x,\[Delta],g,\[CapitalGamma]}][  Tensor[V,{i},{Void}],Tensor[x,{dummy},{Void}]];


PartialDFieldV[{x_,\[Delta]_,g_,\[CapitalGamma]_},V_,dummy_][{Void,i_}]:=PartialD[{x,\[Delta],g,\[CapitalGamma]}][   Tensor[V,{dummy},{Void}],Tensor[x,{i},{Void}]];


ExpandLieD[{x_,\[Delta]_,g_,\[CapitalGamma]_},dummy_][      LieD[Tensor[T_,sup_,sub_],V_]    ]:=Module[{indT},
indT=Transpose[{sup,sub}];
PartialD[{x,\[Delta],g,\[CapitalGamma]}][Tensor[T,sup,sub],Tensor[x,{dummy},{Void}]]*Tensor[V,{dummy},{Void}]+
Map[ChangeIndexToDummy[Tensor[T,sup,sub],#,dummy]& ,  indT].
Map[PartialDFieldV[{x,\[Delta],g,\[CapitalGamma]},V,dummy],indT]

]/;Not[VectorQ[V]]


ChangeIndexToDummy[T_,{i_,Void},a_]:=T/.Verbatim[ i]->a;
ChangeIndexToDummy[T_,{Void,i_},a_]:=T/.Verbatim[ i]->a;


ExpandLieD[{x_,\[Delta]_,g_,\[CapitalGamma]_},dummy_][      LieD[Tensor[T_,sup_,sub_],V_]    ]:=Module[{indT,dumV},
indT=Transpose[{sup,sub}];
dumV=Transpose[{dummy,V}];

Fold[
Function[{Tens,dummyV},
PartialD[{x,\[Delta],g,\[CapitalGamma]}][ Tens,Tensor[x,{dummyV[[1]]},{Void}] ]*Tensor[dummyV[[2]],{dummyV[[1]]},{Void}]+
Map[ChangeIndexToDummy[Tens,#,dummyV[[1]]]& ,  indT].
Map[PartialDFieldV[{x,\[Delta],g,\[CapitalGamma]},dummyV[[2]],dummyV[[1]]],indT]],
Tensor[T,sup,sub],dumV]
]/;VectorQ[V]


ExpandLieD[{x_,\[Delta]_,g_,\[CapitalGamma]_},dummy_][      LieD[Tensor[\[Phi]_],V_]    ]:=Module[{},
PartialD[{x,\[Delta],g,\[CapitalGamma]}][ Tensor[\[Phi]],Tensor[x,{dummy},{Void}] ]*Tensor[V,{dummy},{Void}]
]/;Not[VectorQ[V]]


ExpandLieD[{x_,\[Delta]_,g_,\[CapitalGamma]_},dummy_][      LieD[Tensor[\[Phi]_],V_]    ]:=Module[{dumV},
dumV=Transpose[{dummy,V}];
Fold[
Function[{Tens,dummyV},
PartialD[{x,\[Delta],g,\[CapitalGamma]}][ Tens,Tensor[x,{dummyV[[1]]},{Void} ]]*Tensor[dummyV[[2]],{dummyV[[1]]},{Void}]],Tensor[\[Phi]],dumV]
]/;VectorQ[V]


SyntaxInformation[UnnestTensor]={"ArgumentsPattern"->{_}};
UnnestTensor[expr_]:=expr//.Tensor[f_]/;\[Not]FreeQ[{f},Tensor]->f


PermutationMatrixToPermutation[M_?MatrixQ]:=Module[{pos},
pos=Part[Position[#,1],1,1]&/@M;
Part[Position[pos,#],1,1]&/@Range[Length@M]]


PermutationToPermutationMatrix[L_List]:=Module[{k,Id,pos},
Id=IdentityMatrix[Length@L];
pos=Flatten@Table[Flatten@Position[L,k],{k,1,Length@L}];
Transpose@Map[Part[Id,#]&,pos]]


PermutationToInversionTable[L_List]:=Module[{n,temp,L2},n=Length[L];
L2=FoldList[{Part[#1,1]/.{u___,#2,v___}:>{temp=u,v},Length@{temp}}&,{L,Null},Range@Length[L]];
Drop[L2[[All,2]],1]]


Attributes[combinePairP]={Flat};

combinePairP[{pair[m_,n_],u___},{pair[mm_,nn_],v___}]:=Module[{},Which[m<=mm,Join[{pair[m,n]},combinePairP[{u},{pair[mm-m,nn],v}]],m>mm,Join[{pair[mm,nn]},combinePairP[{pair[m-mm-1,n],u},{v}]]]]

combinePairP[{},v_]:=v
combinePairP[u_,{}]:=u
combinePairP[{u__}]:={u}


InversionTableToPermutation[V_List]:=Module[{k,step},step=combinePairP@@Table[{pair[Part[V,k],k]},{k,1,Length@V}];
Map[Part[#,2]&,step]]


costFunctionTens[M_][IT_]:=Module[{P,k},
If[And@@MapThread[And[#2>=0,#1>=#2]&,{Table[k,{k,Length[IT]-1,0,-1}],IT}],P=InversionTableToPermutation[IT];
TensMatrixWeight[PermutationToPermutationMatrix[P].M.Transpose[PermutationToPermutationMatrix[P]]],0]]


largeCanonicalPermutationMatrix[M_] := Module[
{a,n=Length[M],aList,it},
aList=Array[a,n];
it=aList/.Last@NMaximize[
{costFunctionTens[M][aList],Sequence@Table[a[k]\[Element]Integers,{k,1,n}]},aList,Method->"SimulatedAnnealing"];
PermutationToPermutationMatrix@InversionTableToPermutation[it]
      ]


TensMatrixWeight[M_] := Module[{ n},
     n = Length@M;
Plus@@Flatten[n!/ToeplitzMatrix[n]/HilbertMatrix[n]*M]
      ]


BlockTensMatrixWeight[M_]:=Module[{M2,i,j,n,m,p,q},
{n,m}=Take[Dimensions[M],2];
M2=Table[
Part[M,p,q]/.{Superscript["\[CenterDot]",i_]:> Plus@@ToCharacterCode[ToString[i]]*(p*q),Subscript["\[CenterDot]",j_]:> Plus@@ToCharacterCode[ToString[j]]*(p*q)}
,{p,1,n},{q,1,m}];
Plus@@Flatten@Table[(2 n-j)^2*(i)^2*Part[M2,i,j],{i,1,n},{j,1,m}]
]


GraphBlockTensMatrixWeight[M_]:=Module[{M2,n},n=Length[M];
M2=Plus@@Flatten[M/.{ Subscript["\[CenterDot]",_]->0,Superscript["\[CenterDot]",_]->0}]
]


countMatrix[A_,B_]:= Outer[Count[{#1},#2]&,A,B]


replaceFreeIndex[M_,{val_,ind_}]:=ReplacePart[M, {Part[ind,1],Part[ind,1],Part[ind,2],Part[ind,2]}-> val ]


smallCanonicalPermutationMatrix[M_] := Module[{PermList, weights, pos},
            PermList = Permutations[ IdentityMatrix[Length[M]]];
        weights = Map[TensMatrixWeight[#.M.Transpose@#] &, PermList];
        pos = Last@Ordering[weights, -1];
        Part[PermList, pos]
        ]


CanonicalPermutationMatrix[M_]:=If[Length@M<=7,
smallCanonicalPermutationMatrix[M],smallCanonicalPermutationMatrix[M]]


generalUpperTriangularize[M_]:=Module[{tri,i,MW,tempWrap},
MW=Map[tempWrap, M, {4}];
tri = MW*UpperTriangularize[Table[1,{Length@M},{Length@M}]];
Do[  tri[[i,i]] = UpperTriangularize[tri[[i,i]]],{i,1,Length@tri}];
tri/.tempWrap->Identity
]


stripTensor[T_]:=Module[{CovariantDtemp,Tensortemp,PartialDtemp,prev},
prev=(T/.{HoldPattern[CovariantD[ Tensor[a_,upind_,_],upcov_,_]]:>CovariantDtemp[ Tensortemp[a,Length@upind],Length@upcov]
,HoldPattern[PartialD[ Tensor[a_,upind_,_],downind2_]]:>PartialDtemp[ Tensortemp[a,Length@upind],Length@downind2]
})/.Tensor[a_,upind_,_]:>Tensortemp[a,Length@upind];
(prev/. {Tensortemp-> "Tensor",CovariantDtemp->"CovariantD",PartialDtemp->"PartialD"})
]


extractFlavor[ind_]:= If[ AtomQ[ind], Identity, Head[ind] ];


respectOrderIndicesTens[T_]:=Module[
{},T/.{ HoldPattern[CovariantD[ Tensor[_,upind_,downind_],upcov_,downcov_]]:>Flatten[{upind*downind,upcov*downcov}],
Tensor[_,upind_,downind_]:> upind*downind,HoldPattern[PartialD[Tensor[_,upind_,downind_],downind2_]]:>Flatten[{upind*downind,downind2}]}
]


extractFlavorTens[T_]:=Module[{indexList,TList},
TList=Which[  MatchQ[T,_Tensor|_CovariantD|_PartialD],{T},MatchQ[T,_Times],List@@T];
indexList=Flatten@Map[  respectOrderIndicesTens ,TList]/.Void->1;
If[ AtomQ[#], Identity, Head[#] ]&@First[indexList]
]


unsortedGenAdjMat[T_]:= Module[
{TList,indexList,indexTopology,freeInd,freeIndPos,indexTopologyWithFreeInd,freeupdownInd,freeIndUpDownLabeled},

TList=Which[  MatchQ[T,_Tensor|_CovariantD|_PartialD],{T},MatchQ[T,_Times],List@@T];
freeInd =Flatten@ExtractFreeIndices[T];
indexList=Map[  respectOrderIndicesTens  ,TList]/.Void->1;
indexTopology=Outer[ countMatrix,indexList,indexList,1];

freeupdownInd=Flatten/@Transpose[Part[ParseTermIndices[#],2]&/@TList];

freeIndUpDownLabeled=({#,First@Flatten@Position[  freeupdownInd, #]}&/@ freeInd)//.{  {a_,2}->Subscript["\[CenterDot]",a],{a_,1}->Superscript["\[CenterDot]",a] };

freeIndPos=Flatten[  Position[indexList,#]&/@freeInd,1];
indexTopologyWithFreeInd =
Fold[  replaceFreeIndex, indexTopology, Transpose[{ freeIndUpDownLabeled,freeIndPos}]];

indexTopologyWithFreeInd
]


TensorTopology[T_,opts:OptionsPattern[]]:=Module[{},
Which[MatchQ[T,_?FreeTensorQ],Message[TensorTopology::badargument];Abort[];,MatchQ[T,_Plus],Message[TensorTopology::badargument];Abort[];,
Expand[T]=!=T,Message[TensorTopology::badargument];   Abort[];,
MatchQ[T,_],TensorTopology[T,opts]]
]


TensorTopology[a_?FreeTensorQ*T_,opts:OptionsPattern[]]:=TensorTopologyInternal[T,opts]
TensorTopology[T_,opts:OptionsPattern[]]:=TensorTopologyInternal[T,opts]


HoldSubMatrices[mat_]:=Map[Hold[#]&,mat,{2}]


Options[TensorTopologyInternal]={"Symmetries"-> False};


TensorTopologyInternal[T_,opts:OptionsPattern[]] := Module[
  {TList,genAdjMat,genAdjMatP,PermM,labelList,syms},
  TList=Which[  MatchQ[T,_Tensor|_CovariantD|_PartialD],{T},MatchQ[T,_Times],List@@T];
    
genAdjMat=unsortedGenAdjMat[T];
PermM = CanonicalPermutationMatrix@Map[BlockTensMatrixWeight, genAdjMat, {2}];
labelList=Map[stripTensor,TList];

genAdjMatP=PermM.HoldSubMatrices[genAdjMat].Transpose[PermM]//ReleaseHold;

If[ OptionValue["Symmetries"]===True,
genAdjMatP=SymmetrizedGenAdjMat[genAdjMatP,PermM.TList];
genAdjMatP=First@AntiSymmetrizedGenAdjMat[genAdjMatP,PermM.TList];
];

syms=Join[TextractSymmetricForTopology[#],TextractAntiSymmetricForTopology[#]]&/@(PermM.TList);

  {genAdjMatP , PermM.labelList,syms,extractFlavorTens[T]}
  ]


TensorTopologySameQ[A_,B_]:=TensorTopology[A]===TensorTopology[B]


Options[TensorCanonicalFormInternalList]={"Symmetries"->False};


TensorCanonicalForm[dummyList_List][T_,opts:OptionsPattern[]]:=Module[{},
Which[
MatchQ[T,_?FreeTensorQ],Message[TensorCanonicalForm::badargument];Abort[];,
MatchQ[T,_Plus],Map[TensorCanonicalForm[dummyList][#,opts]&, T],
Expand[T]=!=T,TensorCanonicalForm[dummyList][Expand[T],opts],
MatchQ[T,_],TensorCanonicalForm2[dummyList][T,opts]]
]


TensorCanonicalForm2[dummyList_List][a_?FreeTensorQ*T_,opts:OptionsPattern[]]:=a*TensorCanonicalFormInternal[dummyList][T,opts]
TensorCanonicalForm2[dummyList_List][T_,opts:OptionsPattern[]]:=TensorCanonicalFormInternal[dummyList][T,opts]


TensorCanonicalFormInternal[dummyList_List][T_,opts:OptionsPattern[]]:= Times@@TensorCanonicalFormInternalList[dummyList,T,opts]


TensorCanonicalFormInternalList[dummyList_List,T_,opts:OptionsPattern[]]:= Module[
{TList,freeInd,indexList,dummyIndList,labelList,genAdjMatP,genAdjMat,PermM,ncovind,genAdjMatPtsign,tsign=1},

TList=Which[  MatchQ[T,_Tensor|_CovariantD],{T},MatchQ[T,_Times],List@@T];
freeInd =Flatten@ExtractFreeIndices[T];

indexList=Map[  respectOrderIndicesTens  ,TList]/.Void->1;

dummyIndList=Sort@Complement[Flatten@indexList,freeInd];
If[Length[dummyIndList]>Length[dummyList], Print["TensorCanonicalForm:: Unsufficient dummy indices"]; Abort[] ];

labelList=Map[  #/.{ HoldPattern[CovariantD[ Tensor[a_,__],_,_]]:>a,
Tensor[a_,__]:>a}&  ,TList];
genAdjMat=unsortedGenAdjMat[T];

PermM = CanonicalPermutationMatrix@Map[BlockTensMatrixWeight, genAdjMat, {2}];

genAdjMatP=PermM.HoldSubMatrices[genAdjMat].Transpose[PermM]//ReleaseHold;

If[OptionValue["Symmetries"]===True,
genAdjMatP=SymmetrizedGenAdjMat[genAdjMatP,PermM.TList];
genAdjMatPtsign=AntiSymmetrizedGenAdjMat[genAdjMatP,PermM.TList];
genAdjMatP=Part[genAdjMatPtsign,1];
tsign=Part[genAdjMatPtsign,2];
];

ncovind=Map[  
(#//.{HoldPattern[CovariantD[ Tensor[_,__],_,covind_]]:>Length[covind]})/.Tensor[__]-> 0& ,PermM.TList];

Append[MapThread[reconstructTensor,{pairingDummies[genAdjMatP,dummyList],ncovind,PermM.labelList}],tsign]
]


pairingDummies[genAdjMatP_,dummyList_]:= Module[
{dummyIndPos,freeIndPos,prefreeIndPos,freeInd,predummyIndPos,fullIndPos,triTop,count=0,return,tempWrap},

freeInd=Cases[  Flatten[genAdjMatP]  , a:(Superscript["\[CenterDot]",_]|Subscript["\[CenterDot]",_])-> a ];
triTop = generalUpperTriangularize[ Map[tempWrap,genAdjMatP,{4}] ]/.tempWrap-> Identity;

predummyIndPos= Position[triTop,1]//.{u___,
{i_,j_,one_,k_},v___,{i_,jj_,one_,kk_},w___}:>
{u,v,w,{{j,k},{ Void,Part[dummyList,++count] }},{{jj,kk},{Part[dummyList,count],Void}}};

dummyIndPos= Cases[predummyIndPos,{_List,_List}];

prefreeIndPos={Flatten@Position[triTop,#],#} &/@freeInd/.{Subscript[_,a_]-> {Void,a},Superscript[_,a_]-> {a,Void}};

freeIndPos=Map[ {{Part[#,1,1],Part[#,1,3]},Part[#,2]}&,prefreeIndPos];

fullIndPos=Sort[Join[dummyIndPos,freeIndPos]];

return=Map[ Part[#,All,2]&,GatherBy[fullIndPos,Part[#,1,1]&]]
]


reconstructTensor[ind_List,n_?NumericQ,label_]:=Module[{},
If[n==0, Tensor[label, Sequence@@Transpose[ind]] ,
CovariantD[
Tensor[label, Sequence@@Transpose[Drop[ind,-n]]]
, Sequence@@Transpose[Take[ind,-n]]] 
]
]


Options[TensorGraphRulesInternal]={"LabelForm"->"FullLabel","FreeIndices"->True};


autoIndexLabels[labs_]:=Module[{uniqlabs,count},uniqlabs=Union[labs];
Fold[(count=1;#1/.{#2:>SequenceForm[#2,":",count++]})&,labs,uniqlabs]/.SequenceForm[a_,":",1]->a]

TensorGraphRules[a_?FreeTensorQ*T_,opts:OptionsPattern[]]:=TensorGraphRules[T,opts]


TensorGraphRules[T_Tensor|T_CovariantD|T_PartialD|T_Times,opts:OptionsPattern[]]:=TensorGraphRulesInternal[T,opts]


TensorGraphRulesInternal[T_,opts:OptionsPattern[]] := Module[
  {TList,k,rules,genAdjMat,labels,PermM,genAdjMatP,labelsP,freeindsUp,freeindsDown,indexedLabels,triTop,preTens,extraj,freepreTensUp,freepreTensDown,freindrulesUp,freindrulesDown},

TList=Which[  MatchQ[T,_Tensor|_CovariantD|_PartialD],{T},MatchQ[T,_Times],List@@T];
genAdjMat=unsortedGenAdjMat[T];

Which[
OptionValue["LabelForm"]==="FullLabel"||OptionValue["LabelForm"]==="SimpleLabel"
,
labels = (TList /. { CovariantD[ Tensor[a_, __], __] -> a,PartialD[ Tensor[a_, __], _] -> a }) /. Tensor[a_, __] -> a ;
PermM = CanonicalPermutationMatrix@Map[GraphBlockTensMatrixWeight, genAdjMat, {2}];
genAdjMatP=PermM.HoldSubMatrices[genAdjMat].Transpose[PermM]//ReleaseHold;
labelsP=PermM.labels;
freeindsUp=  Flatten[genAdjMatP/.{Subscript[_,_]->Sequence[],Superscript[_,a_]->a}]/.{a_?NumericQ->Sequence[]};
freeindsDown=  Flatten[genAdjMatP/.{Superscript[_,_]->Sequence[],Subscript[_,a_]->a}]/.{a_?NumericQ->Sequence[]};
,
OptionValue["LabelForm"]==="FullTensor"
,
freeindsUp=  Flatten[genAdjMat/.{Subscript[_,_]->Sequence[],Superscript[_,a_]->a}]/.{a_?NumericQ->Sequence[]};
freeindsDown=  Flatten[genAdjMat/.{Superscript[_,_]->Sequence[],Subscript[_,a_]->a}]/.{a_?NumericQ->Sequence[]};
];

indexedLabels =Which[
OptionValue["LabelForm"]==="FullLabel",
triTop=generalUpperTriangularize[genAdjMatP];MapThread[SequenceForm[#1,":",#2]&,{labelsP,Table[k,{k,Length@labelsP}]}],
OptionValue["LabelForm"]==="SimpleLabel",
triTop=generalUpperTriangularize[genAdjMatP];autoIndexLabels[labelsP],
OptionValue["LabelForm"]==="FullTensor",
triTop=generalUpperTriangularize[genAdjMat];
TList
];

 preTens = Position[triTop, 1]  //. {u___,
      {i_, j_, one_, k_}, v___, {i_, jj_, one_, kk_}, w___} :>
     {u, v, w, {j, jj}};
 
extraj=Length[T];
freepreTensUp= Position[triTop, Superscript[_,_]]  //. {u___,{i_, j_, one_, k_}, v___} :>
     {u, v, {j, ++extraj}};

extraj=Length[T];
freepreTensDown= Position[triTop, Subscript[_,_]]  //. {u___,{i_, j_, one_, k_}, v___} :>
     {u, v, {j, ++extraj}};

Which[
OptionValue["FreeIndices"], 
rules=Map[ Rule @@ # &,  Cases[ preTens, {_, _}]] /. n_?IntegerQ :>  Part[indexedLabels, n];
freindrulesUp = Map[ Rule @@ # &,  Cases[ freepreTensUp, {_, _}]] /. n_?IntegerQ :> If[n<= Length[T], Part[indexedLabels, n], Superscript[Style["\[CenterDot]",12],Part[freeindsUp, n-Length[T]]]];
freindrulesDown = Map[ Rule @@ # &,  Cases[ freepreTensDown, {_, _}]] /. n_?IntegerQ :> If[n<= Length[T], Part[indexedLabels, n], Subscript[Style["\[CenterDot]",12],Part[freeindsDown, n-Length[T]]]],
Not@OptionValue["FreeIndices"],
rules=Map[ Rule @@ # &,  Cases[ preTens, {_, _}]] /. n_?IntegerQ :>  Part[indexedLabels, n];
freindrulesUp = {};freindrulesDown = {};
];

Sort@Join[rules,freindrulesUp,freindrulesDown]
 ]


pureTensorFactorsNumber[T_]:=Module[{TList},TList=Which[MatchQ[T,_Tensor|_CovariantD|_PartialD],{T},MatchQ[T,_Times],List@@T];
Length@Select[TList,Position[{#},Tensor[__],Infinity,1]=!={}&]]


TensorGather[T_List]:=Module[{step1,step2,step3,rule1},
step1=GatherBy[T,pureTensorFactorsNumber[#]&];
step2=Map[Sequence@@GatherBy[#,Count[#,CovariantD[__],Infinity]&]&,step1];
step3=Map[Sequence@@GatherBy[#,Count[#,PartialD[__],Infinity]&]&,step2];
Map[Sequence@@GatherBy[#,TensorGraphRules[#,"LabelForm"->"FullLabel"]&]&,step3]]


TensorTopologyGather[T_List]:=Module[{},Gather[T,TensorTopologySameQ]]

TensorClusterFactors[T_]:=Module[{},
Which[MatchQ[T,_?FreeTensorQ],Message[TensorClusterFactors::badargument];Abort[];,MatchQ[T,_Plus],Message[TensorClusterFactors::badargument];Abort[];,
Expand[T]=!=T,Message[TensorClusterFactors::badargument];   Abort[];,
MatchQ[T,_Tensor|_CovariantD],{1,T},
MatchQ[T,Times[__]],TensorClusterFactorsInternal[T]]
]


TensorClusterFactorsInternal[a_?FreeTensorQ*T_]:=TensorClusterFactorsInternal[T,a]
TensorClusterFactorsInternal[T_]:=TensorClusterFactorsInternal[T,1]


TensorClusterFactorsInternal[T_, a_] := Module[{pre,partit},
pre=f@@Union[ Map[Union[List@@#]&,TensorGraphRules[T,"LabelForm"->"FullTensor"]]/.{Subscript[__]->Sequence[],Superscript[__]->Sequence[]}];

partit=pre//.f[u___,x_,v___,y_,w___]/;(Intersection[x,y]=!={}):>f[u,v,w,Union@Flatten[{x,y}]];

If[a=!=1,Prepend[List@@partit,{a}], List@@partit]
]


SymmetrizedGenAdjMat[genAdjMatP_, TList_] := Module[
  {i, j, PermM, permList, weighteddList,preweighteddList, maxweight, optiPerms, holdTopo, n, genAdjMatfinal, holdList},permList = Map[    TSymmetricPermutations @@ TextractSymmetricList[#] &, TList];preweighteddList=Outer[ TpermuteInsideBlocks[genAdjMatP, {##}] &, Sequence @@ permList, 1];

weighteddList= Flatten[preweighteddList, Length[TList]-1];

maxweight = Max[Part[weighteddList, All, 1]];

optiPerms = Part[weighteddList, Part[Position[weighteddList, maxweight], 1, 1], 2]; n = Length[genAdjMatP];
genAdjMatfinal = Table[
     Part[optiPerms, i].Part[genAdjMatP, i, j].Transpose@Part[optiPerms, j]
     , {i, 1, n}, {j, 1, n}] ;
genAdjMatfinal
  ]


AntiSymmetrizedGenAdjMat[genAdjMatP_,TList_]:=Module[
{i,j,PermM,permList,preweighteddList,weighteddList,maxweight,optiPerms,holdTopo,n,genAdjMatfinal,holdList,sign},

permList=Map[    TSymmetricPermutations@@TextractAntiSymmetricList[#]&, TList];

preweighteddList=Outer[ TpermuteInsideBlocks[genAdjMatP, {##}] &, Sequence @@ permList, 1];

weighteddList= Flatten[preweighteddList, Length[TList]-1];

maxweight=Max[Part[weighteddList,All,1]];
optiPerms=Part[weighteddList,Part[Position[weighteddList,maxweight],1,1],2];

n=Length[genAdjMatP];

 genAdjMatfinal = Table[
     Part[optiPerms, i].Part[genAdjMatP, i, j].Transpose@Part[optiPerms, j]
     , {i, 1, n}, {j, 1, n}] ;

sign =Times@@Map[Signature@PermutationMatrixToPermutation[#]&,optiPerms];

{genAdjMatfinal,sign}
]


TextractSymmetricList[T_] :=TextractSymmetric[T]/.Symmetric->List


TextractSymmetric[T_]:=Module[{TLabel,s,a,b,TOrder,TFreeDOrder,pre},
TLabel=extractTensorLabel[T];
TOrder=extractTensorOrder[T];
TFreeDOrder=extractTensorFreeDOrder[T];
pre=Flatten[Cases[
ReleaseHold[Map[List@@#&,DownValues[TensorSymmetry]]/.TensorSymmetry[a__]->Identity[{a}]],{{TLabel,TFreeDOrder},s_}->{TOrder,s}],1]//.{AntiSymmetric[_,_]-> Sequence[],{}-> Sequence[]};
If[pre=={},{TOrder},pre]]


TextractSymmetricForTopology[T_]:=Cases[Flatten[TextractSymmetric[T]],Symmetric[_,_]]


TextractAntiSymmetricList[T_] := TextractAntiSymmetric[T]/.AntiSymmetric->List


TextractAntiSymmetric[T_]:=Module[{TLabel,s,a,b,TOrder,TFreeDOrder,pre},
TLabel=extractTensorLabel[T];
TOrder=extractTensorOrder[T];
TFreeDOrder=extractTensorFreeDOrder[T];
pre=Flatten[Cases[ReleaseHold[Map[List@@#&,DownValues[TensorSymmetry]]/.TensorSymmetry[a__]->Identity[{a}]],{{TLabel,TFreeDOrder},s_}->{TOrder,s}],1]//.{Symmetric[_,_]-> Sequence[],{}-> Sequence[]};
If[pre=={},{TOrder},pre]]


TextractAntiSymmetricForTopology[T_]:=Cases[Flatten[TextractAntiSymmetric[T]],AntiSymmetric[_,_]]


TreplacePermutationList[L_][pos_,perm_]:=Map[ReplacePart[L,Thread[Rule[pos,#]]]&,perm];


TSymmetricPermutations[n_?IntegerQ]:= {IdentityMatrix[n]};


TSymmetricPermutations[n_?IntegerQ,symms_List]:=Module[{L,permMatrixM,perms},
L=Range[n];
If[Length[symms]>0,

perms=Map[TreplacePermutationList[L][#,Permutations[#]]&,symms];

permMatrixM=Outer[Dot,Sequence@@Map[PermutationToPermutationMatrix,perms,{2}],1]];

Which[Length[symms]==0,{IdentityMatrix[n]},
Length[symms]==1,permMatrixM,
Length[symms]>1,Flatten[permMatrixM,1]]
];


extractTensorLabel[T_]:=Module[{},
T/.{HoldPattern[Tensor[a_,_,_]]->a,HoldPattern[CovariantD[Tensor[a_,_,_],_,_]]->a,HoldPattern[PartialD[Tensor[a_,_,_],_]]->a}
]


extractTensorOrder[T_]:=Module[{},
T/.{HoldPattern[Tensor[_,a_,_]]:>Length[a],HoldPattern[CovariantD[Tensor[_,a_,_],b_,_]]:>Length[Join[a,b]],HoldPattern[PartialD[Tensor[_,a_,_],b_]]:>Length[Join[a,b]]}
]


extractTensorFreeDOrder[T_]:=Module[{},
T/.{HoldPattern[Tensor[_,a_,_]]:>Length[a],HoldPattern[CovariantD[Tensor[_,a_,_],b_,_]]:>Length[a],HoldPattern[PartialD[Tensor[_,a_,_],b_]]:>Length[a]}
]


TpermuteInsideBlocks[M_,perms_List]:= Module[
{n=Length[perms],wrap,Mh,i,j,holdList,permConfigTopo},
(*Mh= M/.{{Void,i_}-> holdList[Void,i],{i_,Void}-> holdList[i,Void]};*)
permConfigTopo=Table[
Part[perms,i].Part[M,i,j].Transpose@Part[perms,j]
,{i,1,n},{j,1,n}];
{TensMatrixWeight@Map[BlockTensMatrixWeight, permConfigTopo, {2}],perms}
]


(* ::Input:: *)
SyntaxInformation[FreeTensorQ]={"ArgumentsPattern"->{_}};
FreeTensorQ[w_]:= Position[w,Tensor]=={};


(* ::Input:: *)
SyntaxInformation[FreeTotalDQ]={"ArgumentsPattern"->{_}};
FreeTotalDQ[w_]:= Position[w,TotalD]=={};


(* ::Input:: *)
FreeAbsoluteDQ[w_]:= Position[w,AbsoluteD]=={};


(* ::Input:: *)
FreeLieDQ[w_]:= Position[w,LieD]=={};


End[]


DeclareBaseIndices[{1,2,3}];


IndexFlavors={};


PatternSymmetries={};


DefinedTensors={};


SetDerivativeSymbols[{",",";","\[DifferentialD]","\[DifferentialD]","D","d","\[Sterling]"}]
SetCovariantDisplay["SemicolonMode"]
SetPartialDisplay["CommaMode"]


Off[General::spell]
Off[General::spell1];


TensorialHelp


EndPackage[]
